Saturday, April 2, 2016

MOBILE Automation Part-1. Set Up and Configuration Details(Appium)

=====================
 
JAVA INSTALLATION
=====================
1. Install JAVA -jdk8
   http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Set the JAVA_Home Variable
  Open the Control Panel -> System or Security –> System; 
  the same thing can be done by right-clicking on ‘MyComputer’ and choosing Properties.
  ->Choose ‘Advanced system settings‘.
  ->Under the Advanced tab Choose the ‘Environment Variable…‘ option.
  ->Select New In the System variables.
  ->Define the Variable name as ‘JAVA_HOME‘ and Variable value as ‘C:\Program Files\Java\jdk1.8.0_45‘

3. Set the Path Variable
  Now we need to specify the location in the PATH variable. 
  For PATH, most probably it will already exists in your machine. So just select it and choose the Edit option.
  In the editor add the value ‘;%JAVA_HOME%\bin‘ or ‘;C:Program Files\Java\jdk1.8.0_45\bin‘.
 
4. Ensure Java is installed
   Go to Start and type cmd in the Run and hit Enter. It will launch the Command Prompt. Type ‘java -version
   it will display the version of Java installed, ie  java version 1.8.0

=============================
ANDROID SDK TOOLS 
=============================
1.Download and install the Android SDK/ADB 

2.Set the ANDROID_Home Variable
  After you’ve installed the Android SDK Environment Kit in Windows, you must set the ANDROID_HOME environment      variable to point
  to the Android SDK installation directory. To set up the Android Environment Variable but to achieve that you are required to have the 
  Android installation path with you

3. Open the Control Panel -> System or Security –> System
 the same thing can be done by right-clicking on ‘MyComputer’ and choosing Properties.
 ->Choose ‘Advanced system settings‘.
 ->Under the Advanced tab Choose the ‘Environment Variable…‘ option.
 ->Select New In the System variables.
 ->Define the Variable name as ‘ANDROID_HOME‘ and Variable value as ‘C:\Users\vishva\AppData\Local\Android\android-sdk‘.

4.Setting PATH Variables for Android SDK
 Now we need to specify the ‘tools‘ folder location in the PATH variable of android sdk package. 
 For PATH, most probably it will already exists in your machine. So just select it and choose the Edit option.
 In the editor add the value ‘;%ANDROID_HOME%\tools‘ or ‘;C:\Users\vishva\AppData\Local\Android\android-sdk\tools‘.
 In the editor add the value ‘;%ANDROID_HOME%\platform-tools‘ or ‘;C:\Users\vishhva\AppData\Local\Android\android-sdk\platform-tools‘.

5. Ensure Android path variables are set
  Now go to Start and type cmd in the Run and hit Enter. It will launch the Command Prompt. Type ‘android‘. (Open a new Command prompt)
  it will open the Android SDK Manager.

=================================
 INSTALL NODE.JS 
==================================
 1. Download(.msi download file format) and install Node.js (either 32bit/64bit) based on your Machine.
 https://nodejs.org/en/download/


==================================
Install Microsoft .net Framework 4.5
===================================
1. Not needed for Windows 7 and Windows 8, as already they come with OS


=====================================
Download And Install Appium Desktop Client 
=====================================
1. Visit the Appium Download page to install the Appium Desktop client. Click on Appium.exe for Windows to download the ‘.exe‘ file for Appium.

2. Go with the latest version of Appium. (AppiumForWindows_x_x_..zip)

3. Save the .zip file, extract it and install it.(Create a Desktop Icon)

======================================
How to Enable Developer Mode / Options on Android Phone or Tablet
=======================================
Enabling Developer Mode Options on Android Phone or Tablet
1. In your Mobile, Go to the Settings.
2. Scroll down to ‘About phone‘ and tap on it.
3. Scroll down to the bottom again, where you see ‘Build number’ (Your build number may vary). Tap On Build number Seven (7) times. 
  After the third tap, you’ll see a playful dialog that says you’re four taps away from being a developer. 
  Keep on tapping, and you’ve got the developer settings options.
4.You can notice the Developer Options on your screen now.


Switch On USB Debugging
1. Go to the Developer Options.
2. Tick the USB Debugging check box.
3. It may display the Pop Up message, if Yes simply click OK.
4. And it’s done, you can see the USB Debugging is ON now.

=========================================
Install ECLIPSE 
=========================================
1. Install Eclipse IDE (LUNA should be good option for new installation)
2. Go to Eclipse->Windows(Menu)->Preference->Click on Android and add the android sdk path
3. Install ADT  eclipse Plugin from the following link
Open Eclipse->go to Help>Install new Software>Paste the link in first text box and hit enter> Software will be listed>select and click Next/Finish.(If you get, any error/warning window just click OK button)
4. Verify by clicking on Eclipse>Window>Preference. Verify if Android is listed. 
5. Click on Android in Eclipse Preference and give the SDK location in your computer.(Example: E:\android-sdk-windows)

==========================================
Add Selenium Jars (Standard procedure to download and configure in build path)
Also download java-client-3.3.0.jar from SeleniumHQ site and configure in build path


Friday, July 10, 2015

JMETER - Web Socket Testing

How test the Web Socket through Web Socket plugin for Jmeter?

 1. How to add the PLUGIN?


1.Download the Jmeter from the following Link. Download Binaries(.zip)

2.Download the following Web Socket Project 

3.Unzip and import the Project as Maven project to your work space in Eclipse. Run the Maven command to package and install.

4.New jar will be created in the Project. Copy the JMeterWebSocketSampler-1.0.2-SNAPSHOT.Jar and paste it in apache-jmeter/bin/ext folder. Restart the Jmeter. After restarting the Jmeter you can notice websocket sampler as shown in below snapshot.



5. This Jmeter Plug-in supports RFC6455 version of Web Socket protocol. 

Features:
a) Supports HTTS/HTTPS (ws/wss) version of the WebSocket protocol.
b) Option to ignore SSL certificate errors.
c) Streaming allows for a single connection to remain open for the duration of the test.
d) Response has to match predefined regular expression 
e) Response timeout.
f) Response message backlog (build the Sampler response from multiple server messages).
g) Connection could be closed if server sends a message matching predefined regular expression.

6. Open the Application in Chrome Browser for which you need to test web socket. Presss F12 and go Web Console. Click on Network, and again click on WebSockets. Refresh the Page. You will be able to see Web Socket in left panel and under Frames; you will be able to see the Request and Response
(example: Request as 2probe and Response as 3 probe).

7. You may have to replicate these requests in Jmeter to establish the web socket connection.

8. Let see how to send request and Response in Jmeter using Web Socket Plugin.

9. In our Application Web Socket has not been implemented directly, Socket.IO Libraries in turn create the Web Sockets. Also, Application maintains a session. So I will be using an HTTP Request initially and extracting the Socket ID.

10. Fill the Header referring the Browser Web Console.

11. Add the Web Socket Sampler.

Parameters:

a. Connection ID: Pass the Session ID as parameter, which was extracted in previous request.
b. Time Outs : You check the Application Timeout or mention random and try executing.
c. Streaming Connection: Select this check box, as we are sending the streaming data.
d. Request Data: Example: 2probe. Imitate what all the requests needed to establish the web socket connection.
e. Web Socket Response Pattern : Don’t ever forget to mention this pattern (.*). If any one know any other pattern please let me know.
f. Close Connection Pattern : (6:::*) I mentioned these pattern only by trail and error method. If any body knows please let me know.
g. Message Backlog: Mention 1000.
h. Path: Here, In the browser transport=polling, have been replaced as transport=websocket.
























































12 The Web Socket remains the connection open for next requests. We can send other requests using this connection open.

Wednesday, January 2, 2013


How to connect to SQL Database-JDBC connection

1. How to connect to SQL Database

Steps to connect SQL Database (using JDBC Driver)
1. Import the SQL package.
2. Create an Connection Object and initialize to NULL.
3. Create an String variable for URL and store the URL.
4. Create an String variable for DATABASE and store Database Name.
5. Create an String variable for DRIVER and store the JDBC driver.
6. Create an String variable for USERNAME and store UserName.
7. Create an String variable for PASSWORD and store Password.
8. Put an try catch Block, inside try add the following logic.
    1. Create an instance of DRIVER
    2. Pass the URL, DATABASE, USERNAME, PASSWORD to getConnection()
       method of DriverManager, and pass it to Connection Object.
   3. Create an STATEMENT Object which acts as a reference  to Create SQL   
       Statement for the Connection.
   4. Through the STATEMENT Object Execute any Query, and pass it to Object
       of RESULT SET.
   5. Loop through RESULT SET Object and can print the data.
   6. Close the Connection through Connection object.

-----------------------------------------------------------------------------------------------------------------------------
import java.sql.*
public class Connect_DB{

public static void main(String[] args){
      
     Connection conn = NULL;
     String url= "jdbc:mysql://localhost:3306";
     String dbName = "MidMac";
     String driver = "com.mysql.jdbc.Driver";
     String username = "root";
     String password = "tiger";
     
     try{
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbNameusername, password);
            Statement Smt = conn.createStatement();
            ResultSet Rs = Smt.executeQuery("SELECT * FROM EMPLOYEE");
            
            while(Rs .next()){
              System.out.println(Rs.getString(1));
            }//end while
      }catch(Exception e){
            conn.close();
      }
     
}

}

-----------------------------------------------------------------------------------------------------------------------------

Tuesday, January 1, 2013


How to ZIP files in SELENIUM with an Example

1. How to ZIP a file in SELENIUM

Steps to ZIP(Compare with Code and understand)
1. Create an File object for the SOURCE FOLDER, in which files are present.
2. Create another File object for the destination folder, for ZIP file.
3. Create a ZipOutputStream Object.
4. Create a BufferedInputStream Object.
5. Create a Byte Array Object of size 1000.
6. Create a String Array, and collect all files from SOURCE FOLDER as   
    LIST  using File Object for source folder.
7. Loop through String Array and for each element perform below action.
8. INSIDE FOR LOOP
   1. Get the SOURCE FOLDER path and append each file to the path
       with default size, and put it in BufferedInputStream Object.
   2. Through ZipOutputStream Object, make an ZIP Entry for each File.
   3. Through While Loop read the data bit by bit untill 1000 bytes from
       BufferedInputStream Object and write to ZipOutputStream Object.
      9. INSIDE WHILE LOOP
       1. Read the BufferedInputStream Object.
       2. Write to ZipOutputStream Object.

4. After writing make a Close Entry using ZipOutputStream Object.
5. Flush the data using ZipOutputStream Object.
6. Close the ZipOutputStream Object.
-----------------------------------------------------------------------
try
  {
    File inFolder=new File("D:\\sel\\framework\\tests");
    File outFolder=new File("D:\\sel\\framework\\results\\results.zip");

    ZipOutputStream out = new ZipOutputStream(new  BufferedOutputStream( 
                                                  new FileOutputStream(outFolder)));
   BufferedInputStream in = null;
   byte[] data  = new byte[1000];
   String files[] = inFolder.list();
  for (int i=0; i<files.length; i++)
  {
     in = new BufferedInputStream(new FileInputStream
                                               (inFolder.getPath() + "/" + files[i]), 1000);  
     out.putNextEntry(new ZipEntry(files[i])); 
     int count;
              while((count = in.read(data,0,1000)) != -1)
               {
                    out.write(data, 0, count);
               }
              out.closeEntry();
  }
 out.flush();
 out.close();
  }
 catch(Exception e)
 {
  e.printStackTrace();
  }

-----------------------------------------------------------------------

Sunday, December 2, 2012

TestNG with an Example

1. How to install TestNG

Steps to install TestNG
1. Open Eclipse
2. Click on Help => install new Software
3. In the Work with text box, enter this url/text, 
(Testng - http://beust.com/eclipse)
4. Click on Add button next to text box.
5. you will see TestNG added in to below text area.
6. Select it and click on next button. Go on with next window.
7. click on finish.

Steps to check if TestNg is installed in eclipse
1. In Eclips => Click on Window=>Show View
2. TestNG should appear in the list, if it does not appear, then
3. Click on other=>java. Now you should be able to see TestNG icon appearing in the list.
...................................................................................................

2. Example of TestNG



Try out the following example with TestNG.
Steps to create a Project, package and files

1. Create a Java Project
   File=>New=>Java Project (example: Sample1)

2. Create a Package.
  File=>New=>Package. (example: com.pack1)

3. Create a TestNG class.
  File=>New=>Other=>TestNG=>TestNG Class. (example: Test1)

4. Create a Build.xml file under Project Folder.
   Right Click on Project Sample1=>New=>File (example: Build.xml)

This example includes the following files.
1. Test1.java   (package: com.pack1)
2. Build.xml     (create this file under Project Folder)

Write a Method under the annotaion @Test as shown below.
...................................................................................................
Test1.java
...................................................................................................

import org.testng.annotations.Test;


public class Test1 {
  @Test
       public void Simple_test() {
 System.out.println("My First TestNG example");
       }

}
...................................................................................................

Build.xml
...................................................................................................

<?xml version="1.0" encoding="UTF-8"?>
<suite name="New Example">

<test name="My First Test">
<classes>
<class name="com.pack1.Test1"></class>
</classes>
</test>
</suite>
...................................................................................................

NOTE: In Build.xml file, you can give any Suite name, any class name as per your understanding. But inside class name you have to specify the correct class name with package as shown in the example.
     You can add any number of Tests inside a Test Suite tag. Each Test should contain a Test tag, classes tag and class tags.

...................................................................................................

3. Steps to RUN the java file



RightClick on JAVA file=>select RUN AS => TestNG
...................................................................................................


4. Steps to Check Reports of TestNG



1. Expand the test-output folder under Project folder in Eclipse.
2. Click on index.html.(you can find all details of test result)

...................................................................................................

Sunday, October 28, 2012

Selenium Web Driver code

Selenium WebDriver CODE

INDEX

1. Browser Back and Forward (NAVIGATION)
2. Handling DRAG and DROP
3. Making Single Select in Drop down (Option List)
4. Making Single Select in Drop down (By INDEX, VALUE, TEXT)
5. Multiple Select List Box Window
6. Multiple Select List Box Window - DESELECT
7. iFRAMES - How to handle Frames in Web Driver
8. iFRAMES - How to perform action in Frames
9. iFRAMES - How to switch to a perticular Frame through index
10. TABS / New Window
11. CALENDAR popups
12. Drop Down MENU
13. Context Click (Right Click)
14. JAVA SCRIPT example
15. Multiple Elements
16. Other Browser (Internet Explorer)
17. Other Browser (Chrome)
18. PROXY settings.
19. Page Onload authentication
20. File Download
21. File Upload
22.  Java Alert


1.Browser Back and Forward (NAVIGATION)


Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.
CODE: driver.navigate().back();
           driver.navigate().forward();
Example

WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000);            //delay
driver.navigate().back();
driver.navigate().forward();
------------------------------------------------------------------------------------------------------------------------------

2.Handling DRAG and DROP


Steps to Handle Drag and Drop through Selenium Web Driver

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch  and create WebElement object for the DESTINATION element.
6.Perform ACTION
  1.Click and Hold the source WebElement
  2.Move to destination WebElement
  3.Release the Element.

Example

WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));

act.clickAndHold(src).build().perform();                //For each action we need to build and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();
------------------------------------------------------------------------------------------------------------------------------

3.Making Single Select in Drop down (Option List)


Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Create an Select object for the Drop Down Element object.
5. Create a List and collect all Options through Select Object.
6. Create a Iterator object for the List.
7. Get the size of the List.
8. Loop through and check for required element.

Example

WebElement element = driver.findElement(By.name("selectedCustomer"));
Select dd= new Select(element);
List<WebElement> allOptions= dd.getOptions();

//To go through the list, we can use an Iterator. 
//Iterator should be of the same type as the List
//which is WebElement in this case.

Iterator<WebElement> it = allOptions.iterator();
//Using while loop, we can iterate till the List has 
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());

while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
 //Check for the required element by Text and click it
if(el.getText().equals("mango")){
  System.out.println(el.getAttribute("value"));
   el.click();
}
}

------------------------------------------------------------------------------------------------------------------------------


4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by INDEX
6. Select by VALUE
7. Select by VISIBLE TEXT

Example


WebElement customerdd = driver.findElement(By.name("customerProject.shownCustomer"));
//convert the element to select object
Select cust = new Select(customerdd);
cust.selectByIndex(1);                                       //Select by Index
Thread.sleep(3000);
cust.selectByValue("2");                                   //Select by Value
Thread.sleep(3000);
cust.selectByVisibleText("mango");                //Select by Visible Text

------------------------------------------------------------------------------------------------------------------------------


5.Multiple Select List Box Window

Steps to make Multiple Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index) 
6. Select by Index(End index)

Example


WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);                     //Select by Index(From Start location)
usr.selectByIndex(2);                     //Select by index(To End Location)

------------------------------------------------------------------------------------------------------------------------------


6.Multiple Select List Box Window - DESELECT

Steps to make Deselect in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index) 
6. Select by Index(End index)

Example

WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);



//You can deselect the options
usr.deselectAll();                                          //Deselect ALL selected elements
//or
usr.deselectByIndex(0);                              //Deselect By using Index
//or
usr.deselectByValue(value);                       //Deselect By using Value
//or
usr.deselectByVisibleText(text);                 //Deselect By using Text

------------------------------------------------------------------------------------------------------------------------------


7.iFRAMES - How to handle Frames in Web Driver

Steps to get Source of each iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame

Example


/*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");

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

List<WebElement> frms= driver.findElements(By.tagName("iframe"));   //Frame List

System.out.println(frms.size());
for(int i=0;i<frms.size();i++)
{
System.out.println(frms.get(i).getAttribute("src"));
}
------------------------------------------------------------------------------------------------------------------------------


8.iFRAMES - How to perform action in Frames

Steps to perform Action in iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch iFrame element and create an Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.

Example


WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));
driver.switchTo().frame(ifr);                                     //Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8");  //Perform Action in iFrame

------------------------------------------------------------------------------------------------------------------------------

9.iFRAMES - How to switch to a perticular Frame through index

Steps to switch to perticular iFrame by index through Selenium Web Driver.


1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.


Example

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

List<WebElement> frms= driver.findElements(By.tagName("iframe"));

System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();

------------------------------------------------------------------------------------------------------------------------------


10. TABS / New Window


When Browser opens in a new window or in a new tab, Web Driver cannot shift the control to the new Window/ Tab. We need to collect the window handles in a page. Whenever a new window opens we need to iterate and shift to the latest window handle.

TABS/New Window - 1

Steps to iterate through the Window Handles

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to First Window Handle, Second increment Points to second iterator.


Set<String> windowHandles = driver.getWindowHandles();
Iterator<String> it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
------------------------------------------------------------------------------------------------------------------------------

TABS/New Window - 2

When two browsers are opened and Web Driver need to shift the control from Parent Window to Child Window. 

Please follow the steps mentioned below.


1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.


Set<String> windowHandles = driver.getWindowHandles();
Iterator<String> it = windowHandles.iterator();


String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);

------------------------------------------------------------------------------------------------------------------------------


TABS/New Window - 3

When second browser is closed/you close it and Web Driver need to shift the control from Child Window to Parent Window. 

Please follow the steps mentioned below.


1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.
8. When Child browser get closed, Switch from Child browser to Parent Window.


Set<String> windowHandles = driver.getWindowHandles();
Iterator<String> it = windowHandles.iterator();

String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);

driver.close(); //close the current window(Child Browser)
driver.switchTo().window(parentBrowser); //Switch to Parent Browser

------------------------------------------------------------------------------------------------------------------------------

11. CALENDAR popups

Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click.


/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='October 2012']]]]/descendant::a[text()='5']")).click();

------------------------------------------------------------------------------------------------------------------------------

Calendar PopUp - 2 (Customized wait)

 In a Calender if we want to click on future month which is not currently displayed, we need to click on next link until we get the required month.
           This can be done by writing Customized wait. Check for particular date element in each month, if not found move to next month.

/*makemytrip calendar*/

driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag){
  try {
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group') and descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future date
if(el !=null)   //Check if the required date element is found or not
       {
el.click(); // if required Date is found, then click  the date
flag=false;
}
    } 
catch (Exception e) { //Catches exception if no element found
try {
Thread.sleep(500);
driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
}
catch (InterruptedException e1) 
      {
// TODO Auto-generated catch block
 e1.printStackTrace();
      }
  }


------------------------------------------------------------------------------------------------------------------------------


12. Drop Down MENU



 In order to click on an menu item, first we need to move the mouse over Parent menu, later we can click on any of the Menu child item.

Please follow the steps mentioned below.


1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action object for Driver
5. Through Action object, move to Parent element.
6. Give a Delay for menu items to be displayed.
7. Fetch the Child item through xpath and Click on it.


WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));
Actions act = new Actions(driver); // Create an Action object
//move to the parent menu item
act.moveToElement(parentMenu).build().perform(); 
Thread.sleep(3000);   //wait till the child items are displayed
driver.findElement(By.linkText("Bharat Tirth")).click();

------------------------------------------------------------------------------------------------------------------------------


13. Context Click (Right Click)

We can use keyboard keys to Make a Right Click.

Please follow the steps mentioned below.


1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action Object for Driver.
5. Through Action Object, make a Context Click on Menu Parent object.
6. Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.


Example

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));

Actions act = new Actions(driver); //Create Action object for Driver

act.contextClick(parentMenu).build().perform(); //Context Click

act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();

------------------------------------------------------------------------------------------------------------------------------


14. JAVA SCRIPT example

We can use java script command to perform actions.
We can write code to fill up the text box through java script.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Create Java Script executor object for the Driver.
4. Store the Java Script command in a String Variable.
5. Java Script Executor object executes the command in the Variable.



JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCmd = "document.getElementsByName('city')[0].value='ban'";
js.executeScript(jsCmd);

------------------------------------------------------------------------------------------------------------------------------


15. Multiple Elements

We can count the number of links present in the page. We can also print the link text of each Web link.


Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch elements with tag //a in the entire page, store it in a List.
4. Get the count of Links present in the Page.
5. Loop through the links and print the Attributes 


List<WebElement> allLinks= driver.findElements(By.xpath("//a"));
//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;i<allLinks.size();i++)
{
        //display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();

}

------------------------------------------------------------------------------------------------------------------------------

16. Other Browser (Internet Explorer)


Using Internet Explorer with Web Driver.

Please follow the steps mentioned below.
1. Set System Property for the Driver and give path of the IE Driver.
2. Create an Web Driver Object.
3. Open an URL


System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");


WebDriver driver =new InternetExplorerDriver();
driver.get("www.google.com");

------------------------------------------------------------------------------------------------------------------------------


17. Other Browser (Chrome)


Using Chrome with Web Driver.

Please follow the steps mentioned below.

1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create an Web Driver Object.
3. Open an URL



System.setProperty("webdriver.chrome.driver", "D:\\sel\\browserdrivers\\Chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.get("www.google.com");

------------------------------------------------------------------------------------------------------------------------------


18. PROXY settings.

Please follow the steps mentioned below.

1. Import Selenium.Proxy
2. Create a Profile object for Firefox
3. Create a string variable with value.
4. Create a Proxy object.
5. Set the values through proxy.
6. Set the proxy preference to proxy object using profile object.
7. Pass the profile object to Firefox Driver.



import org.openqa.Selenium.Proxy

FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
Proxy proxy = new Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);



------------------------------------------------------------------------------------------------------------------------------

19. Page Onload authentication

Sometimes when you are Automating Web pages, you may come across Page onload Authentication window. This window is not java popup/div. It is windows popup. Selenium directly cannot handle this windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using Autoit.

Please follow the steps mentioned below.

1.Download Autoit from the following URl
  ( http://www.autoitscript.com/site/autoit/downloads/ )
2.Install downloaded software.
3. Open Script Editor
   Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.
4.Open Object Identifier.
  Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to     identify.
6.Collect the Title Name of window from (AutoIt Window Info.)
7.Write the Script in the Editor.
----------------------------------------------------AUTOIT CODE-----------------------------------------------------

WinWaitActive("Authentication Required")
Send("admin")
Send("{TAB} admin{TAB} {ENTER}")

------------------------------------------------------------------------------------------------------------------------------
8.Save the file as default save.(Authentication1.exe)
9.RUN/Compile the SCRIPT, it creates an exe.
10.Mention the exe path in the Program before creation of Driver.

EXAMPLE:


Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM WEBDRIVER\\AUTOIT\\Authentication1.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");

------------------------------------------------------------------------------------------------------------------------------

20. File Download

Please follow the steps mentioned below.


1. Create a PROFILE object of Browser.
2. Set Preference, by giving Download destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2 => Indicates a custom Folder Location
4. Set Preference, A comma-separated list of MIME types to save to disk without asking what to use to open the file. Default value is an empty string.

After coding the above mentioned steps, now start the driver and click on Download button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.


FirefoxProfile Prof = new FirefoxProfile();
Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");

WebDriver driver = new FirefoxDriver(Prof);
driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-drivers']/table/tbody/tr[1]/td[4]/a")).click();

------------------------------------------------------------------------------------------------------------------------------

21. File Upload

Please follow the steps mentioned below.


1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable.
5. Fetch the upload button and click


WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/");
String FilePath = "C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------


22. Handling JAVA ALERT

Sometimes you may get alerts as anticipated(through Insert/update/delete operation in database). These may be JAVA alerts.
Please follow the steps mentioned below to handle  Alerts.


1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. You get an alert asking to click on 'YES' or 'NO' button.
4. First Confirm if it is JAVA alert window.
5. Write a code to switch the control to Alert window.
6. In the Alert window, either ACCEPT by clicking on 'YES'
    or CANCEL by clicking on 'NO'.


WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Alert alert = driver.switchTo().alert();
alert.accept();
//or
alert.dismiss();
------------------------------------------------------------------------------------------------------------------------------

Total Pageviews