Wednesday, 28 January 2015

TestNG

TestNG is an open-source automated testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use. Functionality such as use of annotations for dependency testing, test in groups, email-able reporting, multi-threaded testing, data-driven testing, flexible plug-in API etc..

TestNG is designed to cover all categories of tests such as unit, functional, end-to-end, integration, etc..

In this post we will see a simple example how to use TestNG to execute test cases. In this post we are using following tools:
  1. Eclipse IDE
  2. Maven
First, Add the TestNG plugin in Eclipse either using the eclipse market place or Install new software option, Now Create a Maven project in Eclipse and add following dependency in pom.xml and build the project:

<dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.7</version>
        <scope>test</scope>
</dependency>

Code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LaunchBrowser {

 WebDriver driver;

 @BeforeClass
 public void setup(){
  System.setProperty("webdriver.chrome.driver",
    "E:/WorkSpace/Drivers/chromedriver.exe");
  driver = new ChromeDriver();
 }


 @Test
 public void LaunchPage(){
  try{
   driver.get("http://www.google.com/");
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
 @AfterClass
 public void tearDown(){
  driver.quit();
 }

}

In this example we are using TestNG annotations to drive the test.

@BeforeClass: To execute the method before the first test method of the class is invoked.
@Test: Mark the method as part of the test.
@AfterClass: To execute the method after all the test method of the current class have been run.

Now to run the test do right-click on the workspace and select Run as >> TestNG Test option. After completion of the execution you can see the report generated at following location:

Project root\test-output\emailable-report.html











Stay tuned to see next post on more about TestNG.

Facebook Page: https://www.facebook.com/crazzzygig

Please like and comment on our post and page if you like the blog.

References: http://testng.org/

Monday, 29 December 2014

Internationalization Automation Testing using WebDriver & Java

Internationalization, a subset of Globalization also known as i18n.

With the increasing competition in software industry, Organizations are targeting global markets to spread the business and influence of the product. This means working beyond the geography, culture, language and to work with clients to make sure that application/software has proper handling in terms of readable, view-able, writable and functional perspectives. So, the question here is – Do we need to develop separate application / software for each language and country? The answer is NO.

In internationalization development team removes the hard coded strings and put them into the resource file, there will be different resource files for all different languages. And, by replacing the default language resource file with target language resource file will activate that locale on the application. This is the most used option in development for internationalization development.

The purpose of telling the process of development here was to make you all aware that we can follow the same strategy in automation testing of i18n applications. Developers use these resource files for different language provided by linguist experts in a key-value format. Here key for all locale are same with different value based on language.

Let’s understand the approach in little bit detail. As all of you would be aware of that computer program or code only understand the Latin-1 or Unicode characters. So, all the extracted values from resource files should be translated. Characters of different languages are categorized in single-byte and double-byte characters set. Languages like French, German contains single-byte characters and need not to translate, but languages like Chinese, Korean and Japanese contains double-byte characters. So, to use them in program or code we need to convert into Unicode.

To convert double-byte characters into Unicode, JDK provides a utility called native2ascii. In this post we will use the same for conversion.

Practical Implementation:

Double-byte characters to Unicode conversion:
Below command can used on CMD for conversion. JDK must be installed into the system.

native2ascii -encoding utf8 japanese_native.txt japanese_ascii.txt

Now, we will do this stuff programmatically using Java.


import java.io.File;

public class RunCommandLine {

    public static void runNative2Ascii(String languageFile, String outputFile){
 Runtime runtime = Runtime.getRuntime();
 Process process;

 try{
     System.out.println("native2ascii -encoding utf8 \"" 
    + new File(languageFile) + "\" \"" + new File(outputFile) + "\"");
    process = runtime.exec("cmd /c native2ascii -encoding utf8 \""
    + new File(languageFile) + "\" \"" + new File(outputFile) + "\"");
 }catch(Exception ex){
           ex.printStackTrace();
 }
   }
}

Sample Japanese native language file and output file after Unicode conversion:












The Java class RunCommandLine.java run the native2ascii command programmatically and Unicode characters of Japanese native language will be saved into output.txt file. To read those Unicode characters find below the code:


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadTextFile {

 public static String readParsedResourceFile(String fileName){
  InputStream iStream = null;
  InputStreamReader iStreamReader = null;
  BufferedReader bReader = null;
  StringBuffer sBuffer = new StringBuffer();
  String content = null;
  String resultString = "";

  try{
   iStream = new FileInputStream(new File(fileName));
   iStreamReader = new InputStreamReader(iStream);
   bReader = new BufferedReader(iStreamReader);

   while((content = bReader.readLine()) != null){
    sBuffer.append(content);
   }
   content = sBuffer.toString();
   content = content.substring(6, content.length());
  }catch(Exception ex){
   ex.printStackTrace();
  }finally{
   try{
    if(iStream != null) iStream.close();
    if(iStreamReader != null) iStreamReader.close();
    if(bReader != null) bReader.close();
   }catch(Exception ex){
    ex.printStackTrace();
   }

  }
  Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(content);

  while (m.find()) {
   try {    
    int cp = Integer.parseInt(m.group(1), 16);
    char[] chars = Character.toChars(cp);
    String rep = new String(chars);    
    resultString += rep; 
   } catch (NumberFormatException e) {
    e.printStackTrace();
   }
  }
  return resultString;
 }
}


Now, we will write the script to see the actual result. In the following we are launching google in Japanese domain and typing Japanese text to the browser which is actually Unicode characters saved in output.txt file. Find below code for the same:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.blogger.util.ReadTextFile;
import com.blogger.util.RunCommandLine;

public class GoogleI18N {
 WebDriver driver;
 
 @BeforeTest
 public void setup(){  
  driver.manage().window().maximize();
 }
  
 @Test(priority=0)
 public void launchURL(){
  driver.get("http://www.google.jp");
 }
 
 @Test(priority=1)
 public void searchInDetuchLanguage(){
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     RunCommandLine.runNative2Ascii(""
  + ".\\resources\\japanese.txt", ".\\resources\\output.txt");
     driver.findElement(By.xpath("//div[@id='sb_ifc0']//input"))
     .sendKeys(ReadTextFile.readParsedResourceFile(".\\resources\\output.txt"));
 }
}


Output:





















Hope this article gives you a rough idea on how to proceed with internationalization testing.

Stay tuned to see more updates.

Please like and comment if you like the post.

Saturday, 15 November 2014

Taking Screenshot using Selenium Webdriver

Selenium Webdriver provides functionality to capture screenshot at run time. It can be very useful if it is implemented in a right ways in your framework. Suppose we have to capture screenshot at run time whenever any validation is failed. It will also help non technical person to understand the reason behind of the failure and will help tester/developer to debug in less time.

In the below example code we are providing wrong value of Sign In button to fail the test, and based on the Boolean result driver is capturing the screenshot.

Find the sample code below for the same:


import java.net.MalformedURLException;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class CaptureScreenshot {
 
public WebDriver driver;
boolean flag1;

 @BeforeClass
 public void setup(){
  driver = new FirefoxDriver();
  driver.get("http:\\www.gmail.com");
 }
 
 @Test
 public void testOne(){
         flag1 = driver.findElement(By.id("signIn")).getAttribute("value").
                 equalsIgnoreCase("Sign");
 }
 
 @AfterMethod
 public void afterFailure(){
  try {
   captureScreen(uniqueFileName(), flag1);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public void captureScreen(String fileName, boolean flag) throws IOException{
  if(flag == false){
   File scrFile = ((TakesScreenshot) driver).getScreenshotAs(
                  OutputType.FILE);
   FileUtils.copyFile(scrFile, new File(fileName),true);
  }else{
   System.out.println("Validation Passed");
  }
  
 }
 
 public String uniqueFileName(){
  String imageName = "C:\\SeleniumImage\\Image" + UUID.randomUUID().
                      toString().replaceAll("-", "") + ".png";
  System.out.println(imageName);
  return imageName;
 }
 
 @AfterClass
 public void tearDown(){
  driver.quit();
 }
}

Stay tuned to see more updates.

Facebook Page: https://www.facebook.com/crazzzygig

Wednesday, 22 October 2014

Selenium Grid Practical Example With Different Browsers


In the previous post we have seen how to configure Selenium Grid and distribute tests to execute on nodes (Either virtual or physical machines). In this post we will learn how to distribute tests on different machines with different browsers.

Configure Hub: It will be same as we have done in previous post.

Configure Nodes: To configure nodes we will follow the same command we have used in previous post but with some extra options.

Now we have condition to setup our environment for different browsers on different machines.

For Firefox: As we know the driver for Firefox browser is already provided by Selenium Webdriver API, so we do not need any driver to initialize the Firefox browser. We will run the command written below to start node for Firefox:

java -jar selenium-server-standalone.jar -role node -hub http://localhost:4444/grid/register -port 5656

For Chrome: Driver to initialize Chrome browser is not provided by Selenium Webdriver API, so start the node for Chrome browser we need to download the Chrome Driver. You can easily find the binary for Chrome driver on web or you can follow the link:

http://docs.seleniumhq.org/download/

You will download the chromedriver binary with respect to the Operating System:













After downloading the Chrome driver we need to create an instance of Webdriver for Chrome browser, we will run the following command:

Java -Dwebdriver.chrome.driver= “C:\My Files\Selenium Browser Drivers\chromedriver.exe” -jar selenium-server-standalone.jar -role node -hub http://192.201.16.21:4444/grid/register -port 5757

For Internet Explorer: Driver to initialize IE browser is also not provided with Selenium Webdriver API, so to start the node for IE browser we need to download the ID Driver. You can easily find the binary for IE driver on web or you can follow the link:


You will download the iedriver binary with respect to the 32 or 64 bit Windows Operating System.

After downloading the ie driver we need to create an instance of Webdriver for internet explorer browser, we will run the following command:

Java –Dwebdriver.ie.driver= “C:\My Files\Selenium Browser Drivers\IEDriverServer.exe” –jar selenium-server-standalone.jar -role node -hub http://192.201.16.21:4444/grid/register -port 5858

Once we are done with the registration of nodes for Firefox, Chrome and Internet Explorer, we will create a Maven project (I am using Maven to make my life easier, you can create project by another method as well).

In below screen shot you can see that I have created a Maven project and added a TestNG.xml to manage Test Suites and Test Cases.













Write the test script, find the sample code below:


import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class DistributeTests {

 WebDriver driver;

 @Parameters("browser")
 @BeforeTest
 public void launchBrowser(String browser)
 {  
  String URL = "http://www.google.com";
  if (browser.equalsIgnoreCase("firefox"))
  {
   System.out.println("Initializing FireFox");
   String Node = "http://10.205.112.18:5656/wd/hub";
   DesiredCapabilities cap = DesiredCapabilities.firefox();
   cap.setBrowserName("firefox");
   cap.setPlatform(Platform.WINDOWS);
   try {
    driver = new RemoteWebDriver(new URL(Node), cap);
   } catch (MalformedURLException e) {
    System.out.println("Requested Browser is undefined");
   }
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

   driver.get(URL); 
  } 
  else if (browser.equalsIgnoreCase("chrome")) 
  {
   System.out.println("Initializing CHROME");
   DesiredCapabilities cap = DesiredCapabilities.chrome();
   cap.setBrowserName("chrome");
   cap.setPlatform(Platform.WINDOWS);
   String Node = "http://10.205.112.19:5757/wd/hub";
   try {
    driver = new RemoteWebDriver(new URL(Node), cap);
   } catch (MalformedURLException e) {
    System.out.println("Requested Browser is undefined");
   }
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

   driver.get(URL); 
  } 
  else if (browser.equalsIgnoreCase("ie")) 
  {
   System.out.println("Initializing IE");
   DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
   cap.setBrowserName("ie");
   cap.setPlatform(Platform.WINDOWS);
   String Node = "http://10.205.112.19:5757/wd/hub";
   try {
    driver = new RemoteWebDriver(new URL(Node), cap);
   } catch (MalformedURLException e) {
    System.out.println("Requested Browser is undefined");
   }
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

   driver.get(URL);
  }

 }

 @Test
 public void runTests(){
  driver.findElement(By.id("gbqfq")).sendKeys("Selenium Grid");
  (new Actions(driver)).sendKeys(Keys.ENTER);
 }

 @AfterTest
 public void tearDown(){
  driver.quit();
 }
}



Now it’s time to manage all test configurations from created TestNG.xml. We have a situation to execute test in parallel on Firefox, Chrome and IE browsers and for that we will have to set the attribute ‘parallel=”tests”;’


















Finally it’s time to execute the tests. Run the test as TestNG Test.


Stay tuned to see more updates.

Facebook Page: https://www.facebook.com/crazzzygig

Monday, 20 October 2014

Reducing Test Automation cost while maintaining the efficiency

With the increasing competition in software development industry, Organizations are looking for the proof solutions to keep up themselves parallel or ahead of their competitors. So to be in the competition companies need to be equipped with latest technologies and other resources and it will cost a lot of investment in terms of money, setup etc.

After all these challenges many Researchers and Engineers are continuously working to develop such things that can reduce cost & risk and maximize the efficiency. From the past few years the concept of virtualization and cloud-based infrastructure has played a major role to cope up with these challenges.

Nowadays, Organizations are adopting virtualization and cloud-based infrastructure to reduce the cost and scale up the efficiency. Now coming to the point, Virtualization and cloud-based infrastructure can scale the test automation by reducing the physical hardware required to setup a test environment. With the amalgamation of these technologies we can test web application on a variety of browser, device and operating system combinations.

Selenium Webdriver has unrivalled support for testing web application in virtual environment, executing test in parallel, maximizing speed, coverage and minimizing the cost. In this post we will see how to accomplish this by using Selenium Webdriver.

Selenium Grid allows us to execute multiple instance of Webdriver or RC driver in parallel which uses same code base, and controls all the test cases running on virtual or distributed systems. Selenium Grids comprises of Hub and Nodes.

Hub: It can be considered as a server / a central point that will receive all test requests and will distribute to appropriate nodes / clients based on the configuration settings.

Nodes: Nodes are the client machines (either physical or virtual) connected to Hub which creates instances of Webdriver to execute the tests.



Implementation of Selenium Grid:

Download “selenium-server-standalone.jar”.

Configuring Hub

Start the Hub using following command:

java -jar selenium-server-standalone.jar -role hub







By default it will start automatically on port 4444. If port is unavailable the user can set by adding it to the command:

java -jar selenium-server-standalone.jar -port 4343 -role hub

Now, verify the hub has started by launching it on browser:

http://localhost:4444














Click on console link and then on view config link to see the configuration:





















Configuring Nodes

Now place the “selenium-server-standalone.jar” on node machines and start node using following command:

java -jar selenium-server-standalone.jar -role node -hub http://localhost:4444/grid/register







After registering the node again view the configuration on Hub:















As you can see in the above image that node has been registered with the hub and Browser support and configuration detail is available to user.

Now all the configuration part has been completed so we can start writing our test cases and executing it on the registered nodes.

Script Creation

Create a project in any IDE you like. Find the sample code below:


















After running the test script you can check session created for all the running nodes by launching the following:
http://localhost:5555/wd/hub








Stay tuned to see more updates.

Monday, 18 August 2014

Installing TestNG Plugin for Eclipse

TestNG is a testing framework for the Java programming language inspired from JUnit and NUnit. The design goal of TestNG is to cover all categories of tests: unit, functional, end-to-end, integration, etc., with more powerful and easy-to-use functionalities.

Installing TestNG Plugin for Eclipse enable to run the test cases as TestNG Test directly from Eclipse.

Installing TestNG Plugin:

Go to Eclipse >> Eclipse Marketplace.

Enter the text "TestNG" in the Find field and press Enter.



Select the latest TestNG plugin listed and confirm the installation.



Wait for installation to complete. You may also click on OK button of a warning popup to continue.

Re-start the Eclipse. Now you are ready to use the TestNG.

Stay tuned to see more updates.

Facebook Page: https://www.facebook.com/crazzzygig

Configuring Maven With Eclipse

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.

Installing Maven in Eclipse is fairly simple. Follow the steps mentioned below:

Go to Eclipse >> Help >> Click Install New Software

Use this URL to get the latest stable build: http://download.eclipse.org/technology/m2e/releases/



Select Maven Integration for Eclipse and click Next.

Again Click Next to see installation details and Accept the License Agreement.



Now wait for the installation to complete:



If you get warning popup click OK to continue.

Now Re-start the Eclipse by clicking the 'Yes' button.



Now to check that Maven has successfully installed. Go to Eclipse Click:

File >> New >> Click Others.

Now expand the Maven folder and select Maven Project. Click Next and fill all the mandatory details to create a project. If you are able to create a maven project successfully, Maven has integrated successfully with Eclipse.

Stay tuned to see more updates. Please like/comment.

Suggestions are welcome.

Facebook Page: https://www.facebook.com/crazzzygig