Tuesday 31 December 2013

Handling Drag & Drop for HTML5 | Robot [Webdriver]

Usual drag & drop doesn't work on pages built with HTML5. Here, I've used Robot for controlling the Mouse Actions to work with HTML5 websites.

Snippet

@Test
public void dragAndDrop() throws AWTException, InterruptedException {

driver.get("http://demo.kaazing.com/forex/");
Actions builder = new Actions(driver);
WebElement sourceElement = driver.findElement(By.xpath("(//li[@name='dragSource'])[13]"));
Action drag = builder.clickAndHold(sourceElement).build();
drag.perform();
    
WebElement targetElement = driver.findElement(By.xpath("//section[@id='section1']/div[2]"));
Point coordinates = targetElement.getLocation();
Robot robot = new Robot(); //Robot for controlling mouse actions
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
Thread.sleep(5000);
}

Note| Java Robot can also be used for various actions like locating tooltips, etc.,

Friday 27 December 2013

JUnit3 | JUnit 4 | TestNG variations [Selenium Users]

History of Unit Testing Frameworks:
sUnit  |  ~1998, Kent Beck [for Smalltalk]
JUnit  |  ~2000, Kent Beck & Erich Gamma [Latest 3.x: 3.8.2 (March 2006)]
TestNG     |  ~2004 [Latest: 5.8 (March 2008)]
JUnit 4.x |  2006 [Latest: 4.5 (August 2008)]

Handling expected Exceptions


























Test class | Methods























SetUp | Teardown


Wednesday 11 December 2013

Re-run failed tests Automatically | TestNG | Log4J

Here, I've used Maven for Test Execution; Make sure Log4J dependency added in your POM.xml file. You must run your tests on TestNG framework to achieve this.

Please find the optimized test in my GIT with the use case mentioned below| https://github.com/prashanth-sams/re-runFailedTests

1| Assume you have a class file with 10 Methods [@Test]
2| Lets say one got failed due to Network issue
3| The class file, RetryAnalyzer will make the failed test-case to re-run with desired count; But, it display errors for all the test failures during re-run. [Explained in this post]
4| You are ought to add a Listener class, RetryTestListener; it will print the failure only once.
5| If the test got passed in the final count, failure exception won't be thrown in the console.

Note| 
Steps 4 and 5 are missing in this post; Find it in GIT.


Test Class

@BeforeTest
public void setUp()
{
driver = new FirefoxDriver();
baseUrl = "https://www.google.co.in";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test(retryAnalyzer=RetryAnalyzer.class)
public void test01() throws Exception
{
driver.get(baseUrl + "/");
String save = driver.findElement(By.id("als")).getText();
System.out.println(save);
        // Assert.fail();
Assert.assertEquals(save, "qwerty");
}


RetryAnalyzer.java

Create a Java class, 'RetryAnalyzer' inside the same package and paste the following snippet with minor edits.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class RetryAnalyzer implements IRetryAnalyzer  { 
private int count = 0; 
private int maxCount = 4; // set your count to re-run test
protected Logger log;
private static Logger testbaseLog;

static {
    PropertyConfigurator.configure("test-config/log4j.properties");
    testbaseLog = Logger.getLogger("TestclassName");
}

public RetryAnalyzer()
{
    testbaseLog.trace( " ModeledRetryAnalyzer constructor " + this.getClass().getName() );
    log = Logger.getLogger("TestclassName");
}

@Override 
public boolean retry(ITestResult result) { 
    testbaseLog.trace("running retry logic for  '" 
            + result.getName() 
            + "' on class " + this.getClass().getName() );
        if(count < maxCount) {                     
                count++;                                    
                return true; 
        } 
        return false; 
}
}


POM.xml

<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.37.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>            
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${basedir}/src/test/java/abilash/yourxmlfile.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>  
</plugins>
</build>


P.S| TestNG will create a xml file, 'testng-failed.xml' after your test failure; It contains all the failed test Methods. It can be used to re-run your Failed tests manually.

Friday 6 December 2013

Appium Native iOS App Testing | WebDriver

Appium is an open source, cross-platform test automation tool for native, hybrid and mobile web apps. Appium tests can be written in your favorite Webdriver-compatible language.


Requirements & installation

1| MAC OS X 10.7 (minimum version required)
2| Xcode updated version (prefer)
3| Node.js
4| Appium.app
5| Eclipse Kepler (prefer)
6| TestNG framework


Pre-Appium setup

iOS .app file is enough to inspect elements. In this example, I have used the project, 'InternationalMountains' from Apple DEV site.

1| Download the project, 'InternationalMountains'
2| Double click and extract it
3| Import it into Xcode by opening the Xcode file
4| Run the project
5| Make sure that the simulator is opened with the application
6| Open Terminal and move to the project folder
7| Run the following command to build the .app file

xcodebuild -sdk iphonesimulator6.1

8| It will build the app and generate the file, 'InternationalMountains.app' under
/InternationalMountains/Build/Products/Release-iphonesimulator/


Appium iOS setup

1| Download & Install Node.js
// npm represents that Node.js Package Manager
$ sudo npm install wd


2| Run the Appium server using node.js;  There are couple of ways to do so..

#1 Using Node.js
//install Appium
$ npm install -g appium (or) $ sudo npm install appium -g
//start Appium server
$ appium & 


#2 Using the App
Download Appium, install and Run it

3| Now, the Appium server gets started in the default port 4723 and IP Address 0.0.0.0
i.e., [http://0.0.0.0:4723]


Appium inspector

Appium inspector is a record and playback tool just like Selenium IDE for web.

1| Open Appium
2| Change the default IP address to 127.0.0.1 and port 4725




3| Now, enable the check box, 'App path'
4| Click on the 'Choose' button and locate the .app local directory. i.e., InternationalMountains.app



5| Click on the 'Launch' button [Appium server launches now]
6| Now, a blue-colored icon found beside the 'Launch' button is enabled
7| Clicking blue-colored icon open up the Appium inspector with Simulator
8| Now, click the 'Record' button in Appium inspector
9| Every action will be generating a script at bottom of the Appium inspector




Run the script in Eclipse IDE

package packagename;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class AppiumTest {
public WebDriver driver = null;

@BeforeMethod
public void setUp() throws Exception {
// set up appium
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "6.1");
capabilities.setCapability(CapabilityType.PLATFORM, "Mac");
capabilities.setCapability("app","/Users/username/Downloads/InternationalMountains/build/Release-iphonesimulator/InternationalMountains.app");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4725/wd/hub"), capabilities);
}

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

@Test
public void test01() throws InterruptedException {
driver.findElement(By.xpath("//window[1]/tableview[1]/cell[2]")).click();
driver.findElement(By.xpath("//window[1]/navigationBar[1]/button[1]")).click();
driver.findElement(By.xpath("//window[1]/tableview[1]/cell[7]/text[1]")).click();
}
}
  

Note: 
1| Currently, there is no Appium inspector support for Windows

Wednesday 4 December 2013

Selenium & Performance Testing | Firebug

Note:  Text in ORANGE can be edited or mentioned important for this entire blog

NetExport Firebug extension is used to find out the actual response time for each and every request sent.  I have used the Firefox profile to do this.

Configure netExport

1| Download Firebug Firefox add-on
2| Download netExport Firefox add-on. [netExport is a part of Firebug]


NetExport Firebug extension is used for exporting the data collected by Net panel

3| Manual Export option is available to download the data in .HAR format. [Here, we are going to do the same using Selenium Webdriver]


4| The downloaded .har log can be viewed later to check performance of the site. [This can done using harviewer]
5| Drag the .har log from local directory and drop it anywhere inside the page mentioned in step 4. (or)
Copy the .har log contents and paste it into the text box and press the preview button.



Snippet | netExport

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default"); //Here, default is the Firefox profile
 
// Set default Firefox preferences
myprofile.setPreference("app.update.enabled", false);

String domain = "extensions.firebug.";

// Set default Firebug preferences
myprofile.setPreference(domain + "currentVersion", "2.0");
myprofile.setPreference(domain + "allPagesActivation", "on");
myprofile.setPreference(domain + "defaultPanelName", "net");
myprofile.setPreference(domain + "net.enableSites", true);

// Set default NetExport preferences
myprofile.setPreference(domain + "netexport.alwaysEnableAutoExport", true);
myprofile.setPreference(domain + "netexport.showPreview", false);
myprofile.setPreference(domain + "netexport.defaultLogDir", "C:\\Test\\"); //Set the local directory here

driver = new FirefoxDriver(myprofile);


Load Add-on from Local Directory [acts just like incognito Window]

#1 Custom Profile
ProfilesIni profile = new ProfilesIni();
final String firebugPath = "C:\\firebug-1.12.5.xpi";
FirefoxProfile myprofile = profile.getProfile("sams");   
myprofile.addExtension(new File(firebugPath));
  
String domain = "extensions.firebug.";

// Set default Firebug preferences
myprofile.setPreference(domain + "currentVersion", "2.0");
myprofile.setPreference(domain + "allPagesActivation", "on");
myprofile.setPreference(domain + "defaultPanelName", "console");
myprofile.setPreference(domain + "net.enableSites", true);
  
driver = new FirefoxDriver(myprofile);

#2  New Profile
final String firebugPath = "C:\\firebug-1.12.5.xpi";
FirefoxProfile myprofile = new FirefoxProfile();       
myprofile.addExtension(new File(firebugPath));

String domain = "extensions.firebug.";

// Set default Firebug preferences
myprofile.setPreference(domain + "currentVersion", "2.0");
myprofile.setPreference(domain + "allPagesActivation", "on");
myprofile.setPreference(domain + "defaultPanelName", "net");
myprofile.setPreference(domain + "net.enableSites", true);

driver = new FirefoxDriver(myprofile); 


Note: 
1| consoleExport is another tool similar to netExport;  consoleExport can be saved in .html format and viewed manually through browser.

Wednesday 20 November 2013

Grouping Test Methods | TestNG

Test Methods are annotated with @Test;  These methods can be grouped and executed separately using TestNG framework.  The methods can also be executed based on the priority.

Please find a Test Suite with real-time implementation as given below,

public class classname{
private WebDriver driver;
private String baseUrl;  
  
  @BeforeTest(groups = { "Group1", "Group2" })
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.justdial.com";
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  }
  
  @Test(groups = { "Group1" }, priority=3)
  public void test1() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1a");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1a");
  }

  @Test(groups = { "Group1" }, priority=2)
  public void test2() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1b");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1b");
  }
  
  @Test(groups = { "Group2" })
  public void test3() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G2a");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G2a");
  }
  
  @Test(groups = { "Group1" }, priority=1)
  public void test4() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G1c");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G1c");
  }
  
  @Test(groups = { "Group2" })
  public void test5() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("what")).sendKeys("G2b");
    driver.findElement(By.id("where")).sendKeys("Chennai");
    System.out.println("I am G2b");
  }

  @AfterTest(groups = { "Group1", "Group2" })
  public void tearDown() throws Exception {
    driver.quit();    
  }

Create .xml file and replace the code

Right-click on your Project/Class file > TestNG > "Convert to TestNG" > Replace with the xml code given below > Finish

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<test name="Test1">
  <classes>
    <class name="package.classname"></class>
  </classes>
  <groups>
    <run>
      <include name="Group1"/>      
    </run>
  </groups>
</test>
</suite> <!-- Suite -->

Friday 8 November 2013

HTMLUnitDriver Extra cover

HTMLUnitDriver is the fastest implementation of WebDriver. It is a java based implementation of a Web Browser without a GUI. For any language binding (other than java) the Selenium Server is required to use this driver. It supports JavaScript. JavaScript engine used by the HTMLUnit (Rhino) is different from other popular browsers. Testing JavaScript using HTMLUnit differ significantly with results.

Note:
Download the latest Selenium drivers[2.35 or above];  Older versions of Selenium won't work.

Handle Transparent Proxy 

HtmlUnitDriver driver = new HtmlUnitDriver();    
driver.setProxy("xxx.xxx.xxx.xxx", port);    //  set proxy for handling Transparent Proxy
driver.setJavascriptEnabled(true);    //  enable JavaScript [this emulate IE's js by default]


Emulate popular Browser's JS

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_17);
driver.setJavascriptEnabled(true);


Emulate specific Browser's JS using Capabilities

#1
DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
driver = new HtmlUnitDriver(capabilities);
#2
DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
capabilities.setBrowserName("Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0");
capabilities.setVersion("24.0");
driver = new HtmlUnitDriver(capabilities); 

Wednesday 30 October 2013

Switch to User Agent - Firefox | Chrome

Switching user-agent can be done through browser custom profile.

Firefox

1| Install the Firefox Add-on, User Agent Switcher
2| Go to Tools > Default User Agent > Edit User Agents... 
3| Select any User agent from list and click Edit button
4| Get the user agent string. e.g., Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
myprofile.setPreference("general.useragent.override", "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)");  // here, the user-agent is 'Yahoo Slurp'
WebDriver driver = new FirefoxDriver(myprofile);


Google Chrome

1| Install the Chrome Add-on, User Agent Switcher
2| Go to chrome://extensions/
3| Click 'Options' under User-Agent Switcher for Chrome
4| Get the desired ser agent string. e.g., iPhone 4
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5


System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");  
options.addArguments("--user-agent=Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5"); //iPhone 4
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);


Note:-
Phantomjs:  phantomjs.page.settings.userAgent

Monday 28 October 2013

Run cross browser tests using TestNG - Chrome | IE | Safari | Opera | Firefox

2| Extract the zipped folders and mention proper location in code [highlighted below].
3| Edit testng.xml as shown below,

testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" verbose="3" parallel="tests" thread-count="5">
  
<test name="Test on Firefox">
  <parameter name="browser" value="Firefox"/>
  <classes>      
    <class name="package.classname"/>       
  </classes>
</test>  
<test name="Test on Chrome">
  <parameter name="browser" value="Chrome"/>
  <classes>      
    <class name="package.classname"/>       
  </classes>
</test>
<test name="Test on InternetExplorer">
  <parameter name="browser" value="InternetExplorer"/>
  <classes>      
    <class name="package.classname"/>       
  </classes>
</test>
<test name="Test on Safari">
  <parameter name="browser" value="Safari"/>
  <classes>      
    <class name="package.classname"/>       
  </classes>
</test>
</test>
<test name="Test on Opera">
  <parameter name="browser" value="Opera"/>
  <classes>      
    <class name="package.classname"/>       
  </classes>
</test>
</suite> <!-- Suite -->


Snippet

@BeforeTest
@Parameters({"browser"})
  public void setUp(String browser) throws MalformedURLException
  {          
 if (browser.equalsIgnoreCase("Firefox")) 
 {
 System.out.println("Running Firefox");
  driver = new FirefoxDriver();
  baseUrl = "http://xyz.com";
 } 
 
 else if (browser.equalsIgnoreCase("chrome")) 
 {
 System.out.println("Running Chrome");
 System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");  
 driver = new ChromeDriver();
 baseUrl = "http://xyz.com";
 } 
 
 else if (browser.equalsIgnoreCase("InternetExplorer")) 
 {
 System.out.println("Running Internet Explorer");
 System.setProperty("webdriver.ie.driver","C:\\IEDriverServer.exe");
    DesiredCapabilities dc = DesiredCapabilities.internetExplorer();
dc.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);  //If IE fail to work, please remove this and remove enable protected mode for all the 4 zones from Internet options
 driver = new InternetExplorerDriver(dc);
 baseUrl = "http://xyz.com";
 } 


   else if (browser.equalsIgnoreCase("safari")) 
  {
  System.out.println("Running Safari");
  driver = new SafariDriver();
  baseUrl = "http://xyz.com";
  } 

   else if (browser.equalsIgnoreCase("opera")) 
  {
  System.out.println("Running Opera");
    // driver = new OperaDriver();       --Use this if the location is set properly | see note #2 below--
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("opera.binary", "C://Program Files (x86)//Opera//opera.exe");
    capabilities.setCapability("opera.log.level", "CONFIG");
    driver = new OperaDriver(capabilities);
  baseUrl = "http://xyz.com";
  } 
}


Note:- 
1| There are drawbacks in SafariDriver
Here, I have used,
Safari | 5.0.3 (7533.19.4)
Selenium | 2.35
OS | Windows Vista
# SafariDriver won't work properly in Windows 7
# SafariDriver does not support interacting with modal dialogs
# Cannot navigate forwards or backwards in browser history and more...

2| OperaDriver doesn't support Opera browser versions 13 and above
# Make sure the location of opera.exe under, %PROGRAMFILES%\Opera\opera.exe; If not, then try to locate the execution file using Capabilities

Thursday 24 October 2013

Database Connection in Selenium Webdriver | MySQL

This illustrates how to connect MySQL database with Selenium using Java bindings.  Make sure mysql-connector-java-5.x.x-bin.jar in your buildpath.

Configure MySQL

1| Download an install MySQL.
2| Create a database and table. e.g.,
create database one;
create table pets (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
3| Follow up whatever queries intended
4| Now, try to connect the schema with java via selenium webdriver for retrieving the table values.


private String dbvalue;
private String dbUrl = "jdbc:mysql://localhost:3306/one"; //Here, one is the schema/db
private String username="root";
private String password="yourpassword";
private String dbClass = "com.mysql.jdbc.Driver";

@Test
public void connectdb() throws Exception {  
driver.get("www.xyz.com");
      
try {
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl,username,password);
Statement stmt = con.createStatement();

//insert values into the table | Get values from the already created schema/db
String insertvalues1 = "Insert into pets values('dashund', 'Sams', 'DOG', 'M' ,'2012-05-12', '2012-05-12');";
String insertvalues2 = "Insert into pets values('brownie', 'Sams', 'CAT', 'F' ,'2013-07-22', '0000-00-00');";
String insertvalues3 = "Insert into pets values('parrot', 'Sams', 'BIRD', 'F' ,'2011-12-02', '0000-00-00');";
stmt.executeUpdate(insertvalues1);
stmt.executeUpdate(insertvalues2);
stmt.executeUpdate(insertvalues3);

String query = "select * from pets";
System.out.println(query);
ResultSet rst = stmt.executeQuery(query);

//In a loop
while (rst.next()) {
dbvalue =rst.getString(1);
System.out.println(dbvalue);
driver.findElement(By.id(Value)).sendKeys(dbvalue);
driver.findElement(By.id(Value)).submit();
        driver.get("www.xyz.com");
}

con.close();

} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
}

Tuesday 22 October 2013

TestNG Suite XML file Execution | Maven

The xml file is added to Maven Surefire for test suite execution.

<build>
   <plugins>

   <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.12.2</version>
      <configuration>                       
         <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>             
         </suiteXmlFiles>        
      </configuration>

   </plugin>    
   </plugins>
</build>



Example POM.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>groupidhere</groupId>
  <artifactId>artifactidhere</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>artifactidhere</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
    <plugin>
        <inherited>true</inherited>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
           <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
  
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12.2</version>
        <configuration>                       
          <suiteXmlFiles>
               <suiteXmlFile>testng.xml</suiteXmlFile>             
          </suiteXmlFiles>        
        </configuration>      
      </plugin>  
    </plugins>
  </build>
 
  <dependencies>          
    <dependency>
    <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>          
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-server</artifactId>
      <version>2.35.0</version>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>2.35.0</version>
      </dependency>
      <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-firefox-driver</artifactId>
      <version>2.35.0</version>
    </dependency>          
  </dependencies>
</project>

Monday 21 October 2013

Proxy Settings for Maven | Eclipse

1| Create a file, settings.xml copying the below tags
2| Place it under the location, C:\Users\username\.m2\settings.xml
3| Edit the file wherever necessary

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <proxies>
        <proxy>
            <active>true</active>
            <protocol>http</protocol>
            <host>proxy.somewhere.com</host>
            <port>8080</port>
            <username>proxyuser</username>
            <password>password</password>
            <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
       </proxy>
  </proxies>
</settings>

4| Go to, Eclipse > Window > Preferences > Maven > User Settings
5| Check User Settings location


6| No need of restarting Eclipse to reflect changes.

Friday 18 October 2013

Video Record Selenium Tests

2| Add MonteScreenRecorder.jar into buildpath
3| Locate startRecording() and stopRecording() on apt location
4| Run the test
5| After finishing testrun check the location, C:\Users\username\Videos for recorded video, "ScreenRecording 2013-10-18 at 15.01.43.avi"

import java.awt.*;
import org.monte.media.Format;
import org.monte.media.math.Rational;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;
import org.monte.screenrecorder.ScreenRecorder;

public class className {
private ScreenRecorder screenRecorder;

@Test
public void test01() throws Exception {
className videoRecord = new className();
videoRecord.startRecording(); //Started recording
driver.get("www.xyz.com");
Thread.sleep(2000);
videoRecord.stopRecording(); //Stopped recording

}


 public void startRecording() throws Exception
{    
GraphicsConfiguration gc = GraphicsEnvironment
              .getLocalGraphicsEnvironment()
              .getDefaultScreenDevice()
              .getDefaultConfiguration();

this.screenRecorder = new ScreenRecorder(gc,
              new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
              new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                   CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                   DepthKey, 24, FrameRateKey, Rational.valueOf(15),
                   QualityKey, 1.0f,
                   KeyFrameIntervalKey, 15 * 60),
              new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
                   FrameRateKey, Rational.valueOf(30)),
              null);
this.screenRecorder.start();    
}

public void stopRecording() throws Exception
{
this.screenRecorder.stop();

}

Thursday 17 October 2013

Sikuli Integration | Selenium

Sikuli locate anything based on image recognition technique; tool mainly used for recognizing the Canvas UI, browser pop ups, Flash Contents, and Java Applets.

Set Sikuli Environment

1| Download Sikuli-IDE
2| Unzip the folder under C:\Program Files\
3| Create a new System Variable under 'Environment Variables'.
Variable: SIKULI_HOME
Value: C:\Program Files\Sikuli-IDE
4| Add Sikuli path under the variable name, 'Path'
Variable value: C:\Program Files\Sikuli-IDE\libs
5| If this is not helping, then go to Eclipse,
Right click on Project > Run As > Run Configurations... > (x)= Arguments
VM arguments:
-Dsikuli.Home="C:\Program Files\Sikuli-IDE"

Configure Sikuli in Eclipse

6| Get sikuli-script.jar from your Sikuli IDE installation path, C:\Program Files\Sikuli-IDE
7| Add sikuli-script.jar into buildpath
8| Create a new folder, "imgs" inside project
9| Take screenshot, optimize them and place it inside the folder, "imgs"




import org.sikuli.script.*;
public static Screen sikuliObject = new Screen();

@Test
public void test01() throws Exception, FindFailed {
driver.get("www.xyz.com");        
try{    
sikuliObject.click("C:\\workspace\\project\\imgs\\1.png", 0); //Clicking an image
sikuliObject.type("C:\\workspace\\project\\imgs\\search.png", "hello"); //Inserting values into a text field
}catch(FindFailed e){
e.printStackTrace();

}

Disable 'Untrusted connection | SSL certificate' Warning

No need of custom Firefox|Chrome profiles to deal with "Untrusted connection" on Webdriver.

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
driver = new FirefoxDriver(capabilities);

Note: By default 'Untrusted connection | SSL certificate' will be disabled.



Wednesday 16 October 2013

Capture and Navigate all the Links on Webpage

Iterator and advanced for loop can do similar job;  However, the inconsistency on page navigation within a loop can be solved using array concept.

private static String[] links = null;
private static int linksCount = 0;

driver.get("www.xyz.com");
List<WebElement> linksize = driver.findElements(By.tagName("a")); 
linksCount = linksize.size();
System.out.println("Total no of links Available: "+linksCount);
links= new String[linksCount];
System.out.println("List of links Available: "); 
// print all the links from webpage 
for(int i=0;i<linksCount;i++)
{
links[i] = linksize.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}
// navigate to each Link on the webpage
for(int i=0;i<linksCount;i++)
{
driver.navigate().to(links[i]);
Thread.sleep(3000);
}

1| Capture all links under specific frame|class|id and Navigate one by one
driver.get("www.xyz.com");  
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a"));
int sizeOfAllLinks = elements.size();
System.out.println(sizeOfAllLinks);
for(int i=0; i<sizeOfAllLinks ;i++)
{
System.out.println(elements.get(i).getAttribute("href"));
}   
for (int index=0; index<sizeOfAllLinks; index++ ) {
getElementWithIndex(By.tagName("a"), index).click();
driver.navigate().back();
}

public WebElement getElementWithIndex(By by, int index) {
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a")); 
return elements.get(index);
}

2| Capture all links [Alternate method]
#Java
driver.get(baseUrl + "https://www.google.co.in");
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a")); 
System.out.println("Total no of links Available: " + all_links_webpage.size());
int k = all_links_webpage.size();
System.out.println("List of links Available: ");
for(int i=0;i<k;i++)
{
if(all_links_webpage.get(i).getAttribute("href").contains("google"))
{
String link = all_links_webpage.get(i).getAttribute("href");
System.out.println(link);
}   
}

#PYTHON
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.google.co.in/")
Link = driver.find_elements_by_tag_name("a")
# prints size of all the links available
print len(Link) 

for index in Link:
    print index.get_attribute("href")

driver.quit()