Tuesday, 11 June 2019

How to uninstall Java from Mac machine

Uninstalling software from Mac machine is bit tricky. It is as easy as Windows.

In this post we will know how to uninstall Java from any Mac machine. Follow the below steps to uninstall successfully from your machine

Note: We can uninstall the software as an Admin only
1. Open terminal
2. Copy and past the following commands one by one
sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane  
sudo rm -fr ~/Library/Application\ Support/Oracle/Java
 
Do not attempt to uninstall Java by removing the Java tools from /usr/bin. This directory is part of the system software and any changes will be reset by Apple the next time you perform an update of the OS.

The Java Deployment cache contains files that may have been stored by Java while Java was running. It may also contain settings that were modified through the Java Control Panel.

These instructions will help you remove the Java Deployment cache, if Java has been uninstalled from the computer. The cache may still be on the computer if it was not removed during the uninstall. If Java is still installed, you may use the uninstall tool, to uninstall Java and select to remove the Java cache.

Remove Oracle Java cache on Mac 

1. Open terminal
2. Copy and past the following command
 rm -r ~/"Library/Application Support/Oracle/Java"

Source: Oracle

Friday, 15 February 2019

How to use linebreak in Excel on Mac

As a regular user of Excel sometimes we need linebreak in an excel spreadsheet cell. On Windows its pretty simple and straight forward solution hit alt+enter. When it comes to Mac, its little bit tricky because there when we try the same the control will move to next cell.

To achieve this on Mac, we have to hit control+option+return keys

Hope this post will help you in addressing the issue you are facing

Sunday, 5 August 2018

How to make our Mac into a WiFi Hotspot

Our Mac can function as a wireless hotspot, which allows us to connect other devices to it and share its Internet connection.
This is most useful feature by Mac if our Mac is connected to a wired network via Ethernet. We can connect any wireless devices to Mac and share the wired Internet connection with any wireless device and almost as our Mac works a wireless router.
Below are the steps to achieve this:

Enable Internet Sharing and Configure Your Hotspot

The Wi-Fi hotspot option is part of the “Internet Sharing” feature in macOS. You’ll find it in the System Preferences window. Click the Apple menu, select System Preferences, and click the Sharing icon.

Select the “Internet Sharing” option in the list. You’ll now need to select the Internet connection you want to share with the devices.
The one big limitation is that you can’t both be connected to a Wi-Fi network and host a Wi-Fi network at the same time.
For example, let’s say your Mac is connected to the Internet through an Ethernet adapter. You’d select Ethernet in the list at the top of the window and share that wired connection over Wi-Fi. If you’re connected via Bluetooth or tethered to an iPhone via a USB cable, you could also select those.
In the “To computers using” box, enable the Wi-Fi option. This will create a Wi-Fi hotspot, and the Internet connection you selected at the top of the window will be shared with devices that connect to the Wi-Fi network.
Click the “Wi-Fi Options” button at the bottom of the window to configure your Wi-Fi hotspot. Select your preferred network name and the best Wi-Fi channel.
Be sure to click the “Security” box and select “WPA2-Personal” and provide a password. By default, the hotspot will be configured without a password and anyone will be able to connect.
When you’re done setting things up, click the checkbox to the left of Internet Sharing and click Start to activate your Wi-Fi hotspot.

Monday, 23 July 2018

How to Install Java in macOS

The best approach to install Java on the Mac is to get the latest version of Java JRE directly from Oracle. This is fairly straight forward and you can either initiate the process from the terminal application in macOS or by going directly to the Java download page on Oracles website.
Open the Terminal app and type the following:
java
Click on the “More Info” button to jump to the Java downloads page in a web browser
Start installing Java on MacOS
Start installing Java on MacOSThis will allow you to download and install the newest most recent version of Java available for the Mac, which is currently JRE8.

Remove Oracle Java cache on Mac

Below are the steps to clear Java cache from any Mac machine:

  1. Click on the Finder icon located in your dock
  2. Click on Go in the Finder menu
  3. Click on Utilities
  4. Double-click on the Terminal icon
  5. In the Terminal window Copy and Paste the commands below:
    rm -r ~/"Library/Application Support/Oracle/Java"

Uninstall Oracle Java using the terminal from any Mac machine

Note: To uninstall Java, you must have Administrator privileges and execute the remove command either as root or by using the sudo tool.

Remove one directory and one file (a symlink), as follows:
  1. Click on the Finder icon located in your dock
  2. Click on Go in the Finder menu
  3. Click on Utilities
  4. Double-click on the Terminal icon
  5. In the Terminal window Copy and Paste the commands below:
    sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
    sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane
    sudo rm -fr ~/Library/Application\ Support/Oracle/Java
Do not attempt to uninstall Java by removing the Java tools from /usr/bin. This directory is part of the system software and any changes will be reset by Apple the next time you perform an update of the OS.

Sunday, 29 October 2017

Uploading file with the help of Robot class in Selenium Automation

While implementing automation, we always come across with a situation where our code need to upload a file using our selenium code.

As we know Selenium is a Web Automation tool and which don't support windows automation. In order to upload a files, we have to perform some Windows based operations.

There are different ways to achieve this. One of the way is to take the support of Robot and StringSelection class.

Below simple code will help to perform file upload as part of Selenium Automation:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
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) throws InterruptedException, AWTException {

// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://html.com/input-type-file/");

                // Absolute path of the file need to uploaded
String fileLocation = "C:\\Users\\testData.xlsx";

                // the code which helps us to perform Copy and Paste options from Clipboard
StringSelection stringSelection = new StringSelection(fileLocation);

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                driver.findElement(By.id("fileupload")).click();
// CTRL+V and ENTER keys are the keyboard events to achieve the Keyboard operations
Robot robot = new Robot();
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);

Thread.sleep(5000);
driver.quit();
}
}

Monday, 9 October 2017

Reading a file as String

Sometimes we need to read test input from a file(.txt/.xml etc) and enter into a text area field. Below code will help to read the content of file and stored in a string.

To achieve this we need to take the help of Apache CommonsIO. This will be available at Apache CommonsIO and download  zip file

Extract the zip file and you will find commons-io-2.5.jar file

Add the jar file to the project 

import java.io.File;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;

public class ReadFileToString {
public static void main(String[] args){
File inputFile = new File("d://test.xml");
//location of the tile
try {
               //Reading file to string
String str = FileUtils.readFileToString(inputFile,Charset.forName("utf-8"));
   System.out.println(str);
} catch (Exception e) {
    e.printStackTrace();
}
}
}

With the help of above code, we can have the content of file. Now we can use the variable to enter the text in text area input field.

In this case, 

driver.findElement(By.id("TextArea")).sendKeys(str);

Friday, 3 January 2014

Running Selenium Script from console/command prompt using .class instead of .java file - TestNG

Purpose: Running Selenium Script from console/command prompt using .class instead of .java file with out JDK - TestNG

Some times we need to run our automation script at client box to demonstrate our ability to automate but we don't want to share our code with out JDK ( required - JRE). We can achieve this by following below steps. With this we can run the script from .class instead of .java file.

We can achieve this using both JUnit and TestNG. In this example we are working with TestNG

Here my example is GoogleConsole.java

Step 1: Prepare required scrip using any IDE and compile
Step 2: Open command prompt in another system and check whether JRE is available
Step 3: Prepare testing.xml file as follows

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Google">
  <test name="GoogleConsloe">
    <classes>
      <class name="GoogleConsole"/>
    </classes>
  </test>
</suite>

Step 3: Copy selenium standalone server, TestNG.jar, .class and testing.xml files to a folder(D:\Google\)
Step 4: Open command prompt and change to D:\Google\
Step 5: Set path using the following command
set classpath=%classpath%;D:\Google\selenium-server-standalone-2.39.0.jar;D:\Google\testng-6.8.jar;.;

*Note: update the paths of the .jar files and .class file according to your path.

Step 6: Run the class file using the following command

java org.testng.TestNG java org.testng.TestNG testng.xml

Now you can see the bowser will open and perform the required operation without code and eclipse
 

Monday, 2 December 2013

Classpath Setup for Java - Windows

Purpose: Classpath Setup for Java - Windows 7

We all know the importance of CLASSPATH for Java. Setting PATH/CLASSPATH is very easy but some of us facing difficulties. For them I want to contribute from my blog. Following steps will provide how easy we can set CLASSPATH/PATH for Java.


Step 1: Download and install Java if not available on your box. You can download from the following URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2: By default JDK will be install at "C:\Program Files\Java\jdkxxx.xx" location only. Unless we change the location at the time of installation this is the default location.

Step 3: Go to JDK installed location and you will find bin folder and open that one. copy the bin folder path.




Step 4: Right Click on My Computer and Select "Properties". Once the Properties window is opened click on Advanced System Settings.

Step 5: Once Advance System Settings window is opened click on Environment Variables option



Step 6: Once Environment Variables window is opened click on New under System Variables and enter Variable Name as PATH and Variable Values  as Path of Java Bin Folder(previously copied path) and click OK




Step 7: Go to JDK folder -> open lib folder and copy the path

 


Step 8: Repeat the steps 4 and 5. Now click on New under User Variables and enter User Variable as CLASS and Variable Values as Path of the lib folder and click on OK




Step 9:  Click on OK of Environment Variables window and System Properties window

Step 10: Open Command Prompt and run any java program and you are able to successfully complete.








 

Wednesday, 27 November 2013

Executing same selenium script with multiple browsers only or cross browser testing - Opening Browsers Parallel

Purpose: Executing same selenium script with multiple browsers only or cross browser testing - Opening Browsers Parallel

In my previous post I provided one way of executing same script with different browsers. Now I am going to show how to run the same script parallel(opening all the browsers at time)

Only the change is very small but I wontedly keeping the post separately to avoid the confusion.

The parallel attribute on the <suite> tag can take one of following values:

<suite name="My suite" parallel="methods">

parallel="methods": TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.

<suite name="My suite" parallel="tests">

parallel="tests": TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.

<suite name="My suite" parallel="classes">

parallel="classes": TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.

<suite name="My suite" parallel="instances">

parallel="instances": TestNG will run all the methods in the same instance in the same thread, but two methods on two different instances will be running in different threads.


From the above parameters: we will use parallel="tests" to achieve our goal.

Step 1: We need to write our case with small change by passing a parameter.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
 private WebDriver driver;

 @Parameters("browser")
 @BeforeMethod
 public void setup(String browser)
 {
  if(browser.equalsIgnoreCase("firefox"))
  {
   driver = new FirefoxDriver();
  }
  else if(browser.equalsIgnoreCase("iexplorer"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
   driver = new InternetExplorerDriver();
  }
  else if(browser.equalsIgnoreCase("chrome"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
   driver = new ChromeDriver();
  }
  driver.manage().window().maximize();
 }

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

 @Test
 public void testMultiBrowser() throws InterruptedException
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
}

2. Now we need to create TestNG.xml and write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
       <test name="TestFirefox" verbose="10">
              <parameter name="browser" value="firefox" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="ChromeTest">
              <parameter name="browser" value="chrome" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="IETest">
              <parameter name="browser" value="iexplorer" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
</suite>

3. Now run the code from TestNG.xml

You can observer all the three browsers will open and perform the task at a time.






 

Friday, 22 November 2013

Executing same selenium script with multiple browsers onfly or cross browser testing

Purpose: Executing same selenium script with multiple browsers

Testing in multiple browsers or Browser compatibility Testing: these are the word we always bother while automating our Test Cases. Following code will help how to execute the same script with multiple browsers.

Step 1: We need to write our case with small change by passing a parameter.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
 private WebDriver driver;

 @Parameters("browser")
 @BeforeMethod
 public void setup(String browser)
 {
  if(browser.equalsIgnoreCase("firefox"))
  {
   driver = new FirefoxDriver();
  }
  else if(browser.equalsIgnoreCase("iexplorer"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
   driver = new InternetExplorerDriver();
  }
  else if(browser.equalsIgnoreCase("chrome"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
   driver = new ChromeDriver();
  }
  driver.manage().window().maximize();
 }

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

 @Test
 public void testMultiBrowser() throws InterruptedException
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
}

2. Now we need to create TestNG.xml and write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
       <test name="TestFirefox" verbose="10">
              <parameter name="browser" value="firefox" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="ChromeTest">
              <parameter name="browser" value="chrome" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="IETest">
              <parameter name="browser" value="iexplorer" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
</suite>

3. Now run the code from TestNG.xml

You can observer all the three browsers will open and perform the task one another.

Sunday, 17 November 2013

Prioritizing Selenium Test cases using TestNG annotations

Purpose: Prioritizing Selenium Test cases using TestNG annotations

Some times we may need to priorities our test cases based on some requirements. Following code will help you all.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class PriorityParam {
 public WebDriver driver;
 public String baseURL;

 @BeforeMethod
 public void setup()
 {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  baseURL = "http://mail.google.com";
 }

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

 @Test(priority=3)
 public void testPriorityParam() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 3");
 }

 @Test(priority=2)
 public void testPriorityParam1() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 2");
 }

 @Test(priority=4)
 public void testPriorityParam2() throws InterruptedException
 {
  driver.get(baseURL);
  Thread.sleep(3000);
  System.out.println("Priority 4");
 }

Thursday, 14 November 2013

Different Operations on Combo Box / Dropdown / Select Option using Selenium Web Driver

Purpose: Different Operations on Combo Box / Dropdown using Selenium Web Driver

We always encounter Combo Box / Dropdown / Select options and following example will help you how to perform different operations.

import java.util.ArrayList;
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.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SelectOption {
 public WebDriver driver;
 public String baseURL;

 @BeforeTest
 public void setup()
 {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  baseURL = "http://hscripts.com/tutorials/html/form-combobox.php";
 }

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

 @Test
 public void testSelectOption() throws InterruptedException
 {
  driver.get(baseURL);
 
  WebElement select = driver.findElement(By.xpath(".//form[1]/select"));
  WebElement multiSelect = driver.findElement(By.xpath(".//form[3]/select"));
  List<WebElement> selectedValues = new ArrayList<>();
 
  Select dropdown = new Select(select);
  dropdown.deselectAll();
  dropdown.selectByValue("two");
  selectedValues = dropdown.getAllSelectedOptions();
  for(WebElement value: selectedValues)
  {
   System.out.println("Selected Value: "+value.getText());
  }
  Thread.sleep(3000);
 
  dropdown = new Select(multiSelect);
  dropdown.deselectAll();
  dropdown.selectByValue("three");
  dropdown.selectByValue("four");
  selectedValues = dropdown.getAllSelectedOptions();
  for(WebElement value: selectedValues)
  {
   System.out.println("Selected Value: "+value.getText());
  }
  Thread.sleep(3000);
  dropdown.deselectAll();
  Thread.sleep(3000);
 }
}

Wednesday, 16 October 2013

Reading Test Data from Text File and Writing in to Text File

Purpose: Reading Test Data from Text File and Writing in to Text File

Some times we may need to read test data from text file. We can achieve this using simple Java snippet. following code will help you to address this

import java.io.*;
public class ReadTextFile {
    public static void main(String[] args){
        String readFile ="D://test.txt";
        String writeFile ="D://test1.txt";
       
        //reading contents from a text file  
        try{
            InputStream ips=new FileInputStream(readFile);
            InputStreamReader ipsr=new InputStreamReader(ips);
            BufferedReader br=new BufferedReader(ipsr);
            String line;
            br.readLine();
           
            String[] n = null;
            while ((line =br.readLine())!=null){
             n = line.split(",");
             for(int i = 0; i < n.length; i++)
             {
              System.out.print(n[i]);
             }
             System.out.println("\n");
            }
            br.close();
        }      
        catch (Exception e){
            System.out.println(e.toString());
        }
        //writing to a text file
        try {
            FileWriter fw = new FileWriter (writeFile);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter fileOut = new PrintWriter (bw);
           
                fileOut.println ("\n1. Writing Content to text file");
                fileOut.println ("\n2. Writing content to text file");
               
            fileOut.close();
        }
        catch (Exception e){
            System.out.println(e.toString());
        }      
    }
}

Inupt file contents(test.txt):


First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name
Password:, Password
Email:, email
First Name:, User First Name
Last Name:, User Last Name
User Name:, User Name1
Password:, Password1
Email:, email1
 

Sunday, 29 September 2013

Reading an element contnet without using XPath by WebDriver

Purpose: Reading an element contnet without using XPath by WebDriver

Some times we can access an element with class only but the class contans compound values but className will not accept compound values.

In order to handle these situatuions we need to write differently. Following code will help you to handle it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Webelements {
 static WebDriver driver;
 // Browser startup
 @BeforeClass
 public void setup() {
 
  driver = new FirefoxDriver();
 }
 // Functionality of Test Case
 @Test
 public void testGoogle() throws InterruptedException, IOException {
 
  driver.get("http://quirksmode.org/css/selectors/multipleclasses.html");
//  System.out.println(driver.findElement(By.className("underline small")).getText());
  System.out.println(driver.findElement(By.cssSelector("p[class='underline small']")).getText());
 
  Thread.sleep(3000);
 }
 @AfterClass
 public void tear() {
  driver.close();
 }

Wednesday, 25 September 2013

Expanding Tree Structure using Selenium Web Driver

Purpose: Expanding Tree Structure using Selenium Web Driver

Following code will help how to expand tree structure with the help of Selenium WebDriver. Every Tree Structure have its own levels. Following code will help to go 2 level expansion.

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.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TreeStructure {
 public String baseURL = "http://www.javascripttoolbox.com/lib/mktree/";

 public WebDriver driver = new FirefoxDriver();
 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testTreeStructure() throws InterruptedException
 {
  driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td[1]/div[2]/div[2]/p[6]/a[2]")).click();
  Thread.sleep(3000);
  List<WebElement> roots = driver.findElements(By.xpath(".//*[@id='tree1']/li"));
  int rootSize = 1;
  for(WebElement root: roots)
  {
   String openRoot = root.getAttribute("class");
   if(openRoot.equalsIgnoreCase("liClosed"))
   {
    String xpath = ".//*[@id='tree1']/li["+rootSize+"]/span";
    openTree(xpath);
    List<WebElement> childRoots = driver.findElements(By.xpath(".//*[@id='tree1']/li["+rootSize+"]/ul/li"));
    int subRootSize = 1;
    for(WebElement childRoot: childRoots)
    {
     String openSubRoot = childRoot.getAttribute("class");
     if(openSubRoot.equalsIgnoreCase("liClosed"))
     {
      String path = ".//*[@id='tree1']/li["+rootSize+"]/ul/li["+subRootSize+"]/span";
      openTree(path);
     }
     subRootSize = subRootSize+1;
    }
   }
   rootSize = rootSize+1;
  }
 }

 public void openTree(String xpath) throws InterruptedException
 {
  driver.findElement(By.xpath(xpath)).click();
  Thread.sleep(3000);
 }
}

Tuesday, 24 September 2013

Handling different Javascript prompts using Selenium WebDriver

Purpose: Handling different Javascript prompts using Selenium WebDriver

We always come across different javascript prompts while accessing different websites. Follwoing code will help to handle while automating those functionalities.

This requires one web page which contains different ways to generate Javascript prompts. Following code for Web page

jscriptpopup.html

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("This is a JavaScript Alert Box!")
document.getElementById("result").innerHTML="Alert Prompted";
}
function show_confirm()
{
 var r=confirm("Press a button");
 if (r==true)
   {
   x="Pressed OK Button!";
   document.getElementById("result").innerHTML=x;
   }
 else
   {
   x="Pressed Cancel Button!";
   document.getElementById("result").innerHTML=x;
   }
}
function show_prompt()
{
 var v = prompt("Enter Value");
 if(v!=null)
  document.getElementById("result").innerHTML="Entered Value is "+v;
  else
 document.getElementById("result").innerHTML="Pressed Cancel button";
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show Alert Box" />
<input type="button" onclick="show_confirm()" value="Show Confrim Box" />
<input type="button" onclick="show_prompt()" value="Show Prompt Box" />
<div id="result"></div>
</body>
</html>

Please save the above code and provide the location of the file in WebDriver code

Webdriver Code:

 import org.openqa.selenium.By;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class JscriptPop {

 public String baseURL = "file:///D:/Raju/Projects/Automation/Sample/jscriptpopup.html"; // Location of the source file
 public Alert alert;
 public static WebDriver driver=new FirefoxDriver();

 @BeforeMethod
 public void setup()
 {
  driver.get(baseURL);
 }

 @AfterMethod
 public void tear()
 {
  driver.quit();
 }

 @Test
 public void testJscriptPop() throws InterruptedException
 {
  // Clicking Alert Box
  driver.findElement(By.xpath("//input[@value='Show Alert Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click ok
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box
  driver.findElement(By.xpath("//input[@value='Show Confrim Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  alert.sendKeys("Test value");
  Thread.sleep(3000);
  // To click OK
  alert.accept();
  Thread.sleep(3000);

  // Clicking Confirm Box Prompt Button
  driver.findElement(By.xpath("//input[@value='Show Prompt Box']")).click();
  Thread.sleep(3000);
  alert = driver.switchTo().alert();
  Thread.sleep(3000);
  // To click Cancel
  alert.dismiss();
  Thread.sleep(3000);
 }
}

Sunday, 22 September 2013

Capturing contents of a Table using Selenium Web Driver

Purpose: Capturing contents of a Table using Selenium Web Driver

Some times we may need to capture each and every value from a table while automating. Following example will help to implement the requirement.

This example also will help us to capture nth Row & Column value.

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.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TableExample {
  public String baseURL = "http://accessibility.psu.edu/tablecomplexhtml";
  public WebDriver driver = new FirefoxDriver();
 
  @BeforeMethod
  public void setup()
  {
   driver.get(baseURL);
  }
 
  @AfterMethod
  public void tear()
  {
   driver.quit();
  }
 
  @Test
  public void testTableExample()
  {
   List<WebElement> rows = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr")); // Returns the number of Rows
   List<WebElement> cols = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td")); // Returns the number of Columns
  
   // Static XPath of a single TR and TD is ".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td[1]"
  
   // code to fetch each and every value of a Table
  
   for(int rowNumber = 1; rowNumber <= rows.size(); rowNumber++)
   {
    for(int colNumber = 1; colNumber <= cols.size(); colNumber++)
    {
     System.out.print(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rowNumber+"]/td["+colNumber+"]")).getText()+"  ");
    }
    System.out.println("\n");
   }
  
   System.out.println("###############################################################################\n");

  // nth element value of a table
  
   System.out.println(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rows.size()+"]/td["+cols.size()+"]")).getText());
  
  }
}

Wednesday, 18 September 2013

Performing Mouse Double Click using Selenium Web Driver

Perpose: Performing Mouse Double Click using Selenium Web Driver

Some web applications may need to perform double click to fire the action. Following code will help how to implement Mouse Double Click using Selenium.

In the following example, page contans a div and if we perform single click noting is going to happen but when we perform double click Map will be zoomed.


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.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DoubleClick {
 public String baseURL = "http://openlayers.org/dev/examples/click.html";
 public WebDriver driver = new FirefoxDriver();
 public WebElement element;
 public String title;
 public Actions action = new Actions(driver);
 @BeforeTest
 public void launchBrowser()
 {
  driver.get(baseURL);
 }

 @AfterTest
 public void closeBrowser()
 {
  driver.quit();
 }

 @Test
 public void doubleClick() throws InterruptedException
 {
  element = driver.findElement(By.xpath(".//*[@id='OpenLayers_Map_2_OpenLayers_ViewPort']"));
  element.click();// For single click Map will not load
  System.out.println("Single Click performed");
  Thread.sleep(3000);
  Action doubleClick = action.doubleClick(element).build();
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
  doubleClick.perform();// After performing double click Map will load
  System.out.println("Double Click performed");
  Thread.sleep(10000);
 }
}