Automation Using Selenium Webdriver

Wednesday, 26 October 2016

Java – Reverse String without using Reverse function

package JavaPrograms;
import java.util.*;
public class ReverseString {
public static void main(String args[])
{
String original, reverse ="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is "+reverse);
}
}

Tuesday, 25 October 2016

Multi Select Action Drop Down

Keyboard Actions::

     Given below are the methods to perform keyboard actions:
 sendKeys - Sends keys to the keyboard representation in the browser.
     Special keys that are not text, represented as Keys are recognized both aspart of sequences of              characters, or individually.
 pressKey - Press a key on the keyboard that is NOT text. The keys suchas function keys "F1", "F2", "Tab", "Control", etc. If keyToPress is asequence of characters, different driverimplementations      may choose tothrow an exception or to read only the first character in the sequence.
 releaseKey - Release a key on the keyboard after executing the keypressevent. It usually holds        good for non-text characters.Here are the syntax to call keyboard functions using Selenium WebDriver.

void sendKeys(java.lang.CharSequence keysToSend)
void pressKey(java.lang.CharSequence keyToPress)
void releaseKey(java.lang.CharSequence keyToRelease)

Mouse Actions
Listed below are some of the key mouse actions that one would come across inmost of the applications:

 Click - Performs a Click. We can also perform a click based oncoordinates.
 contextClick - Performs a context click/right-click on an element orbased on the coordinates.
 doubleClick - Performs a double-click on the webelement or based on thecoordinates. If left empty,      it performs double-click on the current location.
 mouseDown - Performs a mouse-down action on an element or based oncoordinates.
 mouseMove - Performs a mouse-move action on an element or based oncoordinates.
 mouseUp - Releases the mouse usually followed by mouse-down andacts based on coordinates.

Here are the syntax to call mouse actions using Selenium WebDriver:
void click(WebElement onElement)
void contextClick(WebElement onElement)
void doubleClick(WebElement onElement)
void mouseDown(WebElement onElement)
void mouseUp(WebElement onElement)
void mouseMove(WebElement toElement)
void mouseMove(WebElement toElement, long xOffset, long yOffset)

Multi Select Action
Sometimes we would be in a situation to select two or more items in a list box ortext area. To understand the same, we would demonstrate multiple selectionfrom the list using
'http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'.
Example
Let us say, we want to select 3 items from this list as shown below:




Let us see how to code for this functionality:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
public class webdriverdemo
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("http://demos.devexpress.com
/aspxeditorsdemos/ListEditors/MultiSelect.aspx");
//driver.manage().window().maximize();
driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click();
driver.findElement(By.id("ContentHolder_lbSelectionModeSelenium100_DDD_L_LBI1T0")).click();
Thread.sleep(5000);
// Perform Multiple Select
Actions builder = new Actions(driver);
WebElement select =
driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
List<WebElement> options = select.findElements(By.tagName("td"));
System.out.println(options.size());
Action multipleSelect = builder.keyDown(Keys.CONTROL)
.click(options.get(2))
.click(options.get(4))
.click(options.get(6))
.build();
multipleSelect.perform();
driver.close();
         }
}

Output
Upon executing the script, the items would be selected as displayed above andthe size of the list box would also be printed in the console.






Automation framework Architecture and how to build a simple framework in Real Time

In this post we will design our automation testing framework (which will be called as SPOMFramework). The design will look like the one shown



FRAMEWORK ARCHITECTURE


Well, automation framework is a way to organize your code in much meaningful manner, so that any person who is luckily working with you should understand what each file (Code file can be either a vbscript file) has.
Automation framework are different types based on the above organizing of your code, it can be organized based upon your data, so that any person who has the better idea to handle the data files such as excel sheet will even have the handle to control the code !!!, well we call these types of frameworks as data driven frameworks.
Similarly there are some frameworks which can be fully written with keywords of functions such as Login, ClickButton, SearchList etc to enable automation engineers to work within framework much easily without ambiguity of same function or code and use the keywords within a framework for performing some operations, we call these type of framework as Keyword driven framework.
The combination of both of the above is called as Hybrid framework and there are some other frameworks which are named according to their usage such as Modular frameworks, structural framework etc.

Long story short, framework is a way to organize your complex code logics in more meaningful way to make our life easier. This can bring many advantages such as
Easy to understand the code
Easy to debug the code
Rapid development of code
Less error prone code
Automation frameworks are developed during the initial stage of any automation to begin, but as we know initial phase of automation will not have all the features which we are going to put in to the framework to make it more great, hence we will start with baby steps of what is called as
Folder structures, they are more of where we are going to place each and every codes within the folder. The folders in the folders structure are given more meaningful names such as “Utilities” folder, “Core” folder, “Test Data” folder etc.
Now once we have the folder structures in place, we can place the code files within those folders.
The folder structures are common for any frameworks or any automation testing tools which we will use. Well, the next big thing is “Reusability” of any code we write, the code must be written in such a way that it can be reused. The code written once should be written with intention in mind that the code can be reused by the team without many any or no changes in the code.
Similarly the code should also be “Generic” means the code should be compatible with more than one application. Since you are investing a lot of time in your framework design and development, tomorrow your company can come up with a new plan and can ask you automate application B while you have already in the process of automating application A. If you have written your framework more specific to Application A, then you will end up changing all your codes for Application B, hence try to avoid writing code more specific to a particular application. Well, there are cases where you can write very specifically for a particular application, in those cases, try to isolate the application specific stuffs in your framework and make it more visible, so that anybody working in framework can understand that its specific to application and not common to the whole framework.
Code written in automation must have clear comments in it, the comments should include the description of the code which can include the actual functionality of the code, if it has a return type then that too has to be specified, which is more normal as any programmers does, since automation test engineers are no different from a programmers, to me they are more than a programmers and a test engineer.
Wells what’s next, a basic structure of how your framework should look like, as every framework or design has its own structure, which can best understood by pictorial representation, I am also going to present you all via a pictorial representation of the framework structure as shown below.
As you could see in the diagram, the framework has got just 3 layers, but you can increase the layers of abstraction in such a way that it can have more than 3 layers to 10 layers. But it’s all depends upon your need and complexity of your automation framework.

The theory of framework layering is this, “The more you create the layers of abstraction, the more efficient your framework will be”.


Well this is the just an introduction about framework and I hope you got the basic idea of what a framework is all about.
What is a TEST Automation Framework?
A TEST Automation Framework is a set of guidelines like coding standards, test-data handling,object repository treatment etc., which when followed during automation scripting produce beneficial outcomes like increase code re-usability, higher portability, reduced script maintenance cost etc. 
Importantly these are just guidelines and not rules; they are not mandatory and you can still scriptwithout following the guidelines. But we will miss out on the advantages of having a Framework.
Ten Steps for Test Automation Framework Methodology:
• Identification of the Scope of Testing: Company oriented, Product oriented, Project Oriented.
• Identification of the Needs of Testing: Identify Types of testing e.g. FT, Web Services etc.
  and application / modules to be tested.
• Identification of the Requirements of Testing: Find out the nature of requirements, 
  identify type of actions for each requirement & identify high priority requirements.
• Evaluation of the Test Automation Tool: Evaluation checklist, Identify the candidate tools available 
  in the market, Sample run, rate & select the tools, Implementation & Training
• Identification of the Actions to be automated: Actions, Validations & requirements supported by the Tool
• Design of the Test Automation Framework: Framework guidelines, validations, Actions Involved, Systems involved, Tool Extensibility Support, Customs messages & UML Documentation.
• Design of the Input Data Bank: Types of Input file. Input files – Categorization &    Design of file prototypes.
• Development of the Automation Framework: Development of script based upon      framework design, 
  Driver scripts, Worker Scripts, Record / Playback, Screen / Window / Transaction, Action / Keyword & Data Driven.
• Population of Input Data Bank: Different Types of data Input, Populate data from different data sources, Manual input of data and Parent – Child data hierarchy.
• Configuration of the Schedulers: Identify scheduler requirements & configure the   schedulers.

Final keyword in java

Final keyword in java

It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is used at variable level, method level and class level. In java language final keyword can be used in following way.
  • Final at variable level
  • Final at method level
  • Final at class level


Final at variable level

Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful to universal constants, such as "PI".

Final Keyword in java Example

public class Circle
{
public  static final double PI=3.14159;

public static void main(String[] args) 
{
System.out.println(PI);
}
}

Final at method level

It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an error if you try to override the method.
When we want to restrict overriding, then make a method as a final.

Example

public class A
{
public void fun1()
{
.......
}
public final void fun2()
{
.......
}

}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
 // it gives an error because we can not override final method
}
}

Example of final keyword at method level

Example

class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");  
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");  
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}  
} 

Output

It gives an error

Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict inheritance then make class as a final.

Example

public final class A
{
......
......
}
public class B extends  A
{
// it gives an error, because we can not inherit final class
}

Example of final keyword at class level

Example

final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");  
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}  
} 

Output

Output:
It gives an error









HCL (IN F2F THEY ASKED QUESTIONS ONLY FROM MY PROJECT & SOME PROJECT RELATED SCENARIOS)


1.Tell me about your self.
2.tell me about your project.
3.what will be your approach if you have to automate signup for 100 profile.
4.Tell me about your framework.
5.what are the integrations availabel in your project.

6.can i searchh any product by product id.
7.If you have qc then why you are using ALM
8.defect life cycle
9.Modules of ur previous project
10.diff between / and //
11.how to handle alert pop up
12.diff b/w assert and verify
13.what are the challanges you have faced in your project.
14.if i click on any product then it will redirect to a new page that display the product image and its attribute how you will verify that not based on your header on your page based on attributes
15.diff flavor of selenium & diff in them
16.have you automate for diff diff browser
17.is there any diff in coding if you are writing code for diff browsers
18.tell me about locators

19.why we are using x path

Monday, 24 October 2016

Captcha using Selenium Webdriver Automating(Breaking)

Automating(Breaking) captcha using Selenium Webdriver

Usually most of the companies either use their own captchas or one of the third party captchas
(GooglejQuery plugins) in the user registration page of their sites .So these pages can't be
 automated fully.
Infact Captcha itself is implemented to prevent automation. As per official captcha site

A CAPTCHA is a program that  protects  websites against bots  by generating and grading tests that humans can pass but 
current computer programs cannot.

Captchas are not brakeable but there are some third party captchas that can be breakable and one of
the example for it is "jQuery Real Person" captcha . Here is the documentation  :)


Here is the sample code to brake the "jQuery Real Person" Captcha using Selenium WebDriver.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class captchaAutomtion { 
 
 WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void Test(){ 
  //Loading jQuery Real Person Captcha demonstration page
  driver.get("http://keith-wood.name/realPerson.html");
  JavascriptExecutor js = (JavascriptExecutor) driver;
  //Setting the captcha values
  js.executeScript("document.getElementsByName('defaultRealHash')[0]
.setAttribute('value', '-897204064')");
  driver.findElement(By.name("defaultReal")).sendKeys("QNXCUL");
  //Submit the form
  driver.findElement(By.xpath(".//*[@id='default']/form/p[2]/input")).
   .submit(); 
 }

}








Getting google search auto suggestions using Webdriver(Selenium 2)

Getting google search auto suggestions using Webdriver(Selenium 2)

In the google search when we start typing any search query google will start auto suggestions. All these search suggestions are part of a WebTable. If we would like to capture all these search suggestions then we have to just iterate through the table.

Here is the sample code which will start typing "vam" and then capture all search suggestions .
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.BeforeTest;
import org.testng.annotations.Test;

public class SearchSuggestion {
 
WebDriver driver;
 
 @BeforeTest
 public void start(){
   driver = new FirefoxDriver(); 
 }
  
 @Test
  public void SearchSuggestion() {
  
  driver.get("http://google.com");
  driver.findElement(By.id("gbqfq")).sendKeys("vam");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
   WebElement table = driver.findElement(By.className("gssb_m")); 
   List rows = table.findElements(By.tagName("tr")); 
   Iterator i = rows.iterator(); 
   System.out.println("-----------------------------------------"); 
   while(i.hasNext()) { 
           WebElement row = i.next(); 
           List columns = row.findElements(By.tagName("td")); 
           Iterator j = columns.iterator(); 
           while(j.hasNext()) { 
                   WebElement column = j.next(); 
                   System.out.println(column.getText()); 
           } 
           System.out.println(""); 
            
   System.out.println("-----------------------------------------"); 
   } 
  } 
}

Here is what we will see in the browser after running the above code.