Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

Friday, 8 May 2015

Handle Frames through Selenium Webdriver API



One question is arise-What is and iFrame? An iFrame (Inline Frame) is a Hyper Text Markup Language document embedded inside the current HyperText Markup Language document on a website. iFrame HTML element is used to insert content from another source, such as an advertisement, into a Web page. A Web designer can change an iFrame's content without making them reload the complete website. A website can have multiple frames on a single page. And a frame could have inner frames (Frame inside a Frame) for ie-
Frame 1|Frame3
Frame2
In Selenium web driver API to work with iFrames, we have different ways to handle frame depending on the need. Please look at the below ways of handling frames
Syntex-driver.switchTo().frame(int arg0);
Choose a frame by their (zero-based) index. That is, if a page has multiple frames (more than one), the first frame start at index "0", the second start index "1" and so on...
If the frame is selected or navigated, all subsequent calls on the WebDriver API interface are made to that frame. i.e the driver focus shall be now on the frame. Whatever operations we try to perform on pages do not work and throws element not found exception as we navigated or switched to Frame.
Parameters: Index - index(0-based)
Returns: driver focused on the given frame (which is current frame)
Throws: NoSuchFrameException - If the frame does not found.
ie: if iframe id=webklipper-publisher-widget-container-frame, it can be written as driver.switchTo().frame("webklipper-publisher-widget-container-frame"); below is the code example to work with switchToFrame using frame id.
public void switchToFramefunction(int frame) 
{
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with their id " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with the id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with the id " + frame
                                      + e.getStackTrace());
               }
        }

driver.switchTo().frame(String arg0);
Choose a frame by its name / ID. The frames located by matching name attributes are always given precedence over those matched by ID.

Parameters: Name or Id - the name of the frame or the id of the frame element.
Returns: driver focused on the given frame (which is current frame)
Throws: NoSuchFrameException - If the frame does not found
Below is the example good code example using frame name.
public void switchToFrame(String frame) {
               try {
                       driver.switchTo().frame(frame);
                       System.out.println("Navigated to frame with name " + frame);
               } catch (NoSuchFrameException e) {
                       System.out.println("Unable to locate frame with id " + frame
                                      + e.getStackTrace());
               } catch (Exception e) {
                       System.out.println("Unable to navigate to frame with id " + frame
                                      + e.getStackTrace());
               }
        }
driver.switchTo().frame(WebElement frameElement);
Choose a frame using their previously located by WebElement.
Parameters: frameElement - The particular frame element to switch to.
Returns: Driver focused on the given frame (which is current frame).
Throws: NoSuchFrameException - If the given element is neither an iframe nor a frame element. and StaleElementReferenceException exception is arise - If particular Web Element has gone stale.
Below is the example of code to send an Element and  to switch.
public void switchToFrameExample(WebElement frameElement) {
try {
if (isElementPresent(frameElement)) {
driver.switchTo().frame(frameElement);
System.out.println("Navigated to frame with element "+ frameElement);
} else {
System.out.println("Unable to navigate to frame with element "+ frameElement);
                       }
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with element " + frameElement + e.getStackTrace());
} catch (StaleElementReferenceException e) {
System.out.println("Element with " + frameElement + "is not attached to the page document" + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with element " + frameElement + e.getStackTrace());
               }
        }
if there are any case when multiple Frames exists (Frame inside a frame), we need to first switch to the parent frame and then we need to switch to the child frame. Below is the code example to work with multiple frames.
public void switchToFrame(String ParentFrame, String ChildFrame) {
try {
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
System.out.println("Navigated to innerframe with id " + ChildFrame
+ "which is present on frame with id" + ParentFrame);        } catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + ParentFrame
+ " or " + ChildFrame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to innerframe with id "
+ ChildFrame + "which is present on frame with id"
+ ParentFrame + e.getStackTrace());
               }
        }
After working with these frames, main important is to return back to the web page. If you do not return back to the default page, driver is throwing an exception. Below is the code example to return back to the default content.
public void switchtoDefaultFrame() {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
} catch (Exception e) {
System.out.println("unable to navigate back to main webpage from frame"
                                                     + e.getStackTrace());
}
}

Wednesday, 6 May 2015

Selenium WebDriver API Synchronization with web page



This is a technique (mechanism) which involves more than one components to work parallel (smoothly) with each other without interruption.
Commonly in Software Test Automation, It has two components
1. Application under Test
2. Test Automation Tool
Above components have their own speed? We should write an automation scripts in such a way that both the components should move with same and desired speed, so that we should not get "Element Not Found" exception which will consume time again in debugging.
Synchronization can be divided into two important categories:
1. Unconditional Synchronization
2. Conditional Synchronization
Unconditional Synchronization:
In this condition,  just specify the timeout value. It causes to wait until certain amount of time and then proceed further.
i.e.: Wait () and Thread.Sleep (“5000”);
Disadvantage for the statements are, there is a high chance of unnecessary waiting time even though the application is ready for execution.
Advantages are-In a situation where we connect for third party systems like interfaces, it isn’t possible to write a condition or check for a condition. Here in this situations, we have to use the application to wait for certain amount of time by specifying the timeout value.
Conditional Synchronization:
We specify a condition along with timeout value, so that tool waits to check for the condition and then come out if nothing happens.
It is very important to set the timeout value in conditional synchronization, because the tool should proceed further instead of making the tool to wait for a particular condition to satisfy.
In Selenium we have implicit Wait and Explicit Wait conditional statements.
1. Implicit Wait.
An implicit wait is to tell WebDriver API to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediate available.
The default setting is zero (0). Once when we define the implicit wait, it will set for the life of the WebDriver API object instance.
It is a mechanism which shall  be written once and applied for entire session automatically. It should be applied immediately once we initiate the WebDriver API.
Implicit wait will not work all the commands and statements in the application. It will workable only for "FindElement" and "FindElements" statements.
If we set implicit wait, find element will not throw an exception if the element is not found in first instance, instead it will poll for the element until the timeout and then proceeds further. We should always remember to add the below syntax immediately below the WebDriver API statement.
Syntax: driver.manage.TimeOuts.implicitwait(5,Timeunit.SECONDS);
Ie.:
WebDriver API driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("
https://silenumnmisc.blogspot.com/ ");
Explicit Wait:
We need to define a wait statement for certain condition to be satisfied until the specified timeout period. If the WebDriver API finds the element within the timeout period the automation script will get executed.
Explicit wait is mostly used when we need to Wait for a specific content and attribute change after performing any action, like when application gives AJAX call to system and get dynamic data and render on to the UI.
ie: Like there are drop-downs Country and State, based on the country value selected, the values in the state drop-down will change, It will take few seconds of time to get the data based on user selection.
Example:
//Explicit wait for state dropdown field//
WebDriver APIWait wait = new WebDriver APIWait(driver, 10);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("statedropdown")));
 Fluent Wait:
Using Fluent Wait we can define the maximum amount of time to wait for a specific condition, as well as the frequency with which to check for the condition.
And also the user may configure to ignore particular types of exceptions such as "No Such Element Exceptions" when searching for an element in dom.
Syntax:
Wait<WebDriver API> wait = new FluentWait<WebDriver API>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS) 
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS) 
//Which will ignore the NoSuchElementExcepti
.ignoring(NoSuchElementException.class);

Sunday, 29 March 2015

HTML & Web Driver

Enter the data in HTML editior through selenumn web driver-
1.Below is the html code for understanding :-
 <iframe id="message_ifr" frameborder="0" allowtransparency="true" title="Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help" style="width: 100%; height: 100px; display: block;" src="javascript:""">
<!DOCTYPE html>
<html>
<head>
<style id="mceDefaultStyles" type="text/css">
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<link href="http://cgpdigitallibrary.com/www/js/tinymce/skins/lightgray/content.min.css" rel="stylesheet" type="text/css">
</head>
<body id="tinymce" class="mce-content-body " contenteditable="true" data-id="message" spellcheck="false">
<p>
<br data-mce-bogus="1">
</p>
</body>
</html>
</iframe>
2.Web driver code for to switch in to iframe and enter the data in html box

driver.switchTo().frame("message_ifr");  // this line for switching in to iframe
WebElement element = driver.findElement(By.id("tinymce"));// in iframe search the particular id
System.out.println("Entering something in text input");//For debugging purpose
element.sendKeys(Keys.CONTROL + "a");//for whole text for input
element.sendKeys("note for user famcom");// type in to free text box
driver.switchTo().defaultContent();// it is necessary to move out from html editor to perform new task



Thursday, 4 September 2014

Mysql Database Connection using Java and Selenium

Mysql Database Connection using Java and Selenium

// import sql package
import java.sql.*;

//http://docsrv.sco.com/JDK_guide/jdbc/getstart/callablestatement.doc.html
public class Database_connection {

public static void main(String[] args) throws SQLException {

 Connection conn = null;
 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "test";
 String driver = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "root";

 try{
 Class.forName(driver).newInstance();// create object of Driver
 conn = DriverManager.getConnection(url+dbName,userName,password);
 // connection will be established

 // *******************Statement******************
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("select * from users");

//  rs.next(); // 1st row
//  System.out.println(rs.getString(2));
//  rs.next(); // 2nd row
//  System.out.println(rs.getString(1));
 while(rs.next()){
System.out.println(rs.getString(1) + "-- "+rs.getString(2)+" -- "+rs.getString(3));
 }

 System.out.println("*********************************");
 // *****************PREPARED STATEMENT**************
 PreparedStatement pstmt = conn.prepareStatement("select * from users where name = ? and sex=?");
 pstmt.setString(1, "B");
 pstmt.setString(2, "F");
 ResultSet rs1 = pstmt.executeQuery();

 while(rs1.next()){
System.out.println(rs1.getString(1) + "-- "+rs1.getString(2)+" -- "+rs1.getString(3));
 }

//***************Callable Statement************************
 //CallableStatement cstmt = conn.prepareCall("{call getTestData(?,?,?,?)}");
   //cstmt.registerOutParameter(1, java.sql.Types.DECIMAL, 3);
   //cstmt.setString(2, "xxxxx");
   //cstmt.executeUpdate();
  // double d =cstmt.getDouble(1);

//     //********************Add row Insert************************
   pstmt = conn.prepareStatement("insert into users values (?,?,?)");
   pstmt.setString(1, "Tom");
   pstmt.setString(2, "London");
   pstmt.setString(3, "M");
 
   int i=pstmt.executeUpdate();
   if(i==1){
    System.out.println("inserted the record");
   }
 }catch(Exception e){
  e.printStackTrace();
 }finally{
 conn.close();
 }
}

}

Tags:-