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.