Friday, January 29, 2016

Java - Automated Car Parking


In a automated car parking facility we have 10 parking racks
"Rack-01", "Rack-02", "Rack-03", "Rack-04", "Rack-05", "Rack-06", "Rack-07", "Rack-08",

"Rack-09", "Rack-10"

need to maintain a record of which parking rack is free and which is occupied through Java


 package CollectionFramework;  
 import java.util.Arrays;  
 import java.util.Collection;  
 import java.util.HashMap;  
 import java.util.Iterator;  
 import java.util.List;  
 import java.util.Map;  
 import java.util.Map.Entry;  
 import java.util.Set;  
 public class CarParking {  
      static Map<String, String> rackMap;  
      static String rackNumber;  
      static List<String> rackList;  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           CarParking parking = new CarParking();  
           rackSpace();  
           parking.parking(new String[] { "Rack-01", "Rack-10" });  
           parkTheCar();  
           checkRackSpaceStatus();  
      }  
      public static void rackSpace() {  
           // Creating the racks  
           rackList = Arrays.asList("Rack-01", "Rack-02", "Rack-03", "Rack-04", "Rack-05", "Rack-06", "Rack-07", "Rack-08",  
                     "Rack-09", "Rack-10");  
           // adding racks in the map  
           rackMap = new HashMap<>();  
           // by default all parking racks are free  
           for (int i = 0; i < rackList.size(); i++) {  
                rackMap.put(rackList.get(i), "Availale For Parking");  
           }  
      }  
      public static void checkRackSpaceStatus() {  
           System.out.println("");  
 System.out.println("******< PARKING STATUS >******");  
           Set<Entry<String, String>> set = rackMap.entrySet();  
           Iterator<Entry<String, String>> iterator = set.iterator();  
           while (iterator.hasNext()) {  
                Entry<String, String> next = iterator.next();  
                System.out.println(next.getKey() + " :"+"\t" + next.getValue());  
                // System.out.println(iterator.next().getValue());  
           }  
      }  
      public static void parkTheCar() {  
      }  
      public void parking(String[] cars) {  
           for (int i = 0; i < cars.length; i++) {  
                rackNumber = cars[i];  
                // System.out.println(rackMap.get(cars[i]));  
                if (rackMap.get(rackNumber).equals("Availale For Parking")) {  
                     rackMap.remove(rackNumber);  
                     // System.out.println(rackMap.get(rackNumber));  
                      rackMap.putIfAbsent(rackNumber, "Occupied");  
 //                    rackMap.put(rackNumber, "Occupied");  
                     System.out.println("Parked car at " + rackNumber );  
                }  
           }  
      }  
 }  
OUTPUT
 Parked car at Rack-01  
 Parked car at Rack-10  
 ******< PARKING STATUS >******  
 Rack-03 :     Availale For Parking  
 Rack-02 :     Availale For Parking  
 Rack-05 :     Availale For Parking  
 Rack-04 :     Availale For Parking  
 Rack-07 :     Availale For Parking  
 Rack-06 :     Availale For Parking  
 Rack-09 :     Availale For Parking  
 Rack-08 :     Availale For Parking  
 Rack-10 :     Occupied  
 Rack-01 :     Occupied  

Sunday, January 24, 2016

Java Object equivalent to Generics



 package com.bmc.sandbox;  
 import org.apache.poi.util.SystemOutLogger;  
 public class Snadbox {  
      String name;  
      static String address;  
      static Integer num1 = 100;  
      static Integer num2 = 200;  
      static String str1 = "Apple";  
      static String str2 = "Orange";  
      public static void main(String[] args) {  
           TestThis test = new TestThis();  
           System.out.println(test);  
           test.a();  
 //      creating an Integer object  
           NonGeneric nongeneric1 = new NonGeneric(num1, num2);  
           System.out.println(nongeneric1.getObj1());  
           System.out.println(nongeneric1.getObj2());  
 //     creating a string object  
           NonGeneric nongeneric2 = new NonGeneric(str1, str2);  
           System.out.println(nongeneric2.getObj1());  
           System.out.println(nongeneric2.getObj2());  
      }  
 }  
 class NonGeneric {  
      Object obj1;  
      Object obj2;  
      public NonGeneric() {  
           // TODO Auto-generated constructor stub  
      }  
      public NonGeneric(Object obj1, Object obj2) {  
           // TODO Auto-generated constructor stub  
           this.obj1 = obj1;  
           this.obj2 = obj2;  
      }  
      public Object getObj1() {  
           return obj1;  
      }  
      public Object getObj2() {  
           return obj2;  
      }  
 }  
 class TestThis {  
      public void a() {  
           System.out.println(this);  
      }  
 }  

Tuesday, January 19, 2016

TestNG @ Factory with @DataProvider



  1. DataProvider: A test method that uses DataProvider will be executed a multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.
  2. Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class.
TestNG factory is used to create instances of test classes dynamically. This is useful if you want to run the test class any number of times. For example, if you have a test to login into a site and you want to run this test multiple times,then its easy to use TestNG factory where you create multiple instances of test class and run the tests (may be to test any memory leak issues).
Whereas, dataprovider is used to provide parameters to a test. If you provide dataprovider to a test, the test will be run taking different sets of value each time. This is useful for a scenario like where you want to login into a site with different sets of username and password each time.

Problems without @Factory

I have a simple test which opens the Google home page, now through data provider I want to use these search strings.


The effective way to do is through @Factory , where the class is instantiated




 package com.sudas.com.sudas.TestNG;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.remote.DesiredCapabilities;  
 import org.openqa.selenium.remote.RemoteWebDriver;  
 import org.testng.annotations.AfterClass;  
 import org.testng.annotations.AfterMethod;  
 import org.testng.annotations.BeforeClass;  
 import org.testng.annotations.BeforeMethod;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.Factory;  
 import org.testng.annotations.Test;  
 public class GoogleTestFactory {  
      WebDriver driver;  
      String searchString;  
      @BeforeClass  
      public void beforeClass() {  
           System.out.println("BEFORE CLASS");  
           DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();  
           try {  
                driver = new RemoteWebDriver(new URL("http://10.129.63.183:4448/wd/hub"), desiredCapabilities);  
           } catch (MalformedURLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      @BeforeMethod  
      public void beforeMethod() {  
      }  
      @Factory(dataProvider = "dp")  
      public GoogleTestFactory(String searchString) {  
           // TODO Auto-generated constructor stub  
           this.searchString = searchString;  
      }  
      @DataProvider(name = "dp", parallel = true)  
      public Object[][] dataProvider() {  
           return new Object[][] { { "AutoSearch01" }, { "AutoSearch02" }, { "AutoSearch03" }, { "AutoSearch04" } };  
      }  
      @Test  
      public void google() {  
           driver.get("http://www.google.com");  
           driver.findElement(By.id("lst-ib")).sendKeys(searchString);  
      }  
      @AfterClass  
      public void afterClass() {  
      }  
      @AfterMethod  
      public void afterMethod() {  
           System.out.println(driver.getTitle());  
           driver.close();  
           driver.quit();  
      }  
 }  

Monday, January 18, 2016

Test NG DataProvider with Groups using XML

This is the XML



 <?xml version="1.0" encoding="UTF-8"?>  
 <suite name="DataProviderSuite">  
      <test name="DataProviderTest">  
           <groups>  
                <run>  
                     <include name="dpGroup1" />  
                     <exclude name="dpGroup2" />  
                </run>  
           </groups>  
           <classes>  
                <class name="com.sudas.com.sudas.TestNG.BareBoneTest"></class>  
           </classes>  
      </test>  
 </suite>  

This is the DataProvider class

 package com.sudas.com.sudas.TestNG;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.Test;  
 public class DataProviderExample {  
      public static void main(String[] args) {  
           understandMultiArray();  
      }  
      // Data provider method  
      /***  
       * Notes: If the data generator is on the same class where the test method  
       * is a non static method would work other wise needs a static method A Test  
       * NG data provider has return type of multidimensional array object  
       *   
       * @return  
       *   
       */  
      @DataProvider(name = "sampleDP")  
      public static String[][] dataGenerator() {  
           // I am declaring a 2-dimensional object of type string  
           String data[][] = { { "v1A", "v2A", "v3A" }, { "v1B", "v2B", "v3B" }, { "v1C", "v2C", "v3C" } };  
           return data;  
      }  
      @Test(testName = "TestForDP", suiteName = "DataProviderTestSuite", dataProvider = "sampleDP")  
      public void testDP(String a, String b, String c) {  
           System.out.println(a);  
           System.out.println(b);  
           System.out.println(c);  
      }  
      // To understand the 2-dimensional array  
      public static void understandMultiArray() {  
           String data[][] = { { "v1A", "v2A", "v3A" }, { "v1B", "v2B", "v3B" }, { "v1C" } };  
           for (int i = 0; i < data.length; i++) {  
                for (int j = 0; j < data[i].length; j++) {  
                     System.out.println(data[i][j]);  
                }  
           }  
      }  
 }  

This is the test class

 package com.sudas.com.sudas.TestNG;  
 import org.testng.annotations.Test;  
 import org.testng.annotations.BeforeMethod;  
 import org.testng.annotations.AfterMethod;  
 import org.testng.annotations.DataProvider;  
 import org.testng.annotations.BeforeClass;  
 import org.testng.annotations.BeforeGroups;  
 import org.testng.Reporter;  
 import org.testng.annotations.AfterClass;  
 import org.testng.annotations.AfterGroups;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.AfterTest;  
 import org.testng.annotations.BeforeSuite;  
 import org.testng.annotations.AfterSuite;  
 public class BareBoneTest {  
      @Test(groups = {  
                "dpGroup1","test" }, dataProvider = "sampleDP", dataProviderClass = com.sudas.com.sudas.TestNG.DataProviderExample.class)  
      public void dataProvider01(String a, String b, String c) {  
           Reporter.log("This is parameter 01" + a, true);  
      }  
      @Test(groups = {  
                "dpGroup2","test" }, dataProvider = "sampleDP", dataProviderClass = com.sudas.com.sudas.TestNG.DataProviderExample.class)  
      public void dataProvider02(String a, String b, String c) {  
           Reporter.log("This is parameter 02" + b, true);  
      }  
      @BeforeMethod  
      public void beforeMethod() {  
           System.out.println("@BeforeMethod");  
      }  
      @AfterMethod  
      public void afterMethod() {  
           System.out.println("@AfterMethod");  
      }  
      @BeforeClass  
      public void beforeClass() {  
           System.out.println("@BeforeClass");  
      }  
      @AfterClass  
      public void afterClass() {  
           System.out.println("@AfterClass");  
      }  
      @BeforeTest  
      public void beforeTest() {  
           System.out.println("@BeforeTest");  
      }  
      @AfterTest  
      public void afterTest() {  
           System.out.println("@AfterTest");  
      }  
      @BeforeSuite  
      public void beforeSuite() {  
           System.out.println("@BeforeSuite");  
      }  
      @AfterSuite  
      public void afterSuite() {  
           System.out.println("@AfterSuite");  
      }  
      @BeforeGroups  
      public void beforeGroups() {  
           System.out.println("@BeforeGroups");  
      }  
      @AfterGroups  
      public void afterGroups() {  
           System.out.println("@AfterGroups");  
      }  
 }  
OUTPUT Report


More TesNG Data Provider Examples



 @DataProvider  
      public Object[][] phoneObjectDP() {  
           // example  
           String s1[][] = { {}, {} };  
           // example  
           String[][] s2 = new String[3][];  
           Object phoneObjects[][] = { {}, {}, {} };  
           return phoneObjects;  
      }  
      @DataProvider  
      public Object[][] fruitsObject() {  
           return new Object[][] { { 1, "Apple" }, { "Banana", 1.32 } };  
      }  

Sunday, January 17, 2016

Selenium logging for RemoteWebDriver


On enable logging on any any driver like RemoteWebDriver/ FirefoxDriver/ Chrome driver we can implement logging in the following ways.

Steps:
1. Create an object of LoggingPreferences Class.
2. Use the method enable from LoggingPreferences which takes two arguments log type and level.
3. Now create an object of DesireCapabilities
4. Use the method setCapabilities (String , Object )from DesiredCapabilities.
5. Use Interface CapabilityType and it's static final String Fields for String argument and log object on object argument.



Now for capturing the log use driver.manage.logs();
Use the method log.get(logtype.DRIVER) I am capturing the log of only Drive. This return me an entry object. I can iterate over the entry object to get log message and log time stamp. The log timestamp is returned as long EPOCH. Convert EPOCH to date time


Selenium GRID JSON for HUB and NODE


Setting the GRID node and hub capability with JSON


java -jar selenium-server-standalone.jar -role node -nodeConfig nodeconfig.json

NODE.json

{
  "capabilities":
      [
        {
          "browserName": "*firefox",
          "maxInstances": 5,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "*googlechrome",
          "maxInstances": 5,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "*iexplore",
          "maxInstances": 1,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "firefox",
          "maxInstances": 5,
          "seleniumProtocol": "WebDriver"
        },
        {
          "browserName": "chrome",
          "browserVersion": 47.0.2526.111,
          "maxInstances": 5,
          "seleniumProtocol": "WebDriver"
        },
        {
          "browserName": "internet explorer",
          "maxInstances": 1,
          "seleniumProtocol": "WebDriver"
        }
      ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 5,
    "port": 5555,
    "host": 192.168.0.101,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4447,
    "hubHost": 192.168.0.100
  }
}


java -jar selenium-server-standalone.jar -role hub -hubConfig hubconfig.json

HUB.json

{
  "host": 192.168.0.100,
  "port": 4447,
  "newSessionWaitTimeout": -1,
  "servlets" : [],
  "prioritizer": null,
  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "throwOnCapabilityNotPresent": true,
  "nodePolling": 5000,

  "cleanUpCycle": 5000,
  "timeout": 300000,
  "browserTimeout": 0,
  "maxSession": 5,
  "jettyMaxThreads":-1
}

Saturday, January 16, 2016

Selenium Finding Browser Details With DesiredCapability

When using remote webDriver / Selenium Grid the command from client (Language Bondings ) has to be sent to Selenium Server when it's a remote setup Or to the Selenium HUB where as HUB will send the command serialized JSON to NODE which will deserializes and use the command.



driver = new RemoteWebDriver(new URL(nodeAddress), desiredCapabilities);RemoteWebDriver remoteDriver = (RemoteWebDriver) driver;Capabilities actualCapability = remoteDriver.getCapabilities();System.out.println(actualCapability.getVersion());

... and getBrowserName .. etc.

Thursday, January 14, 2016

Selenium Using Browser and Profiles in RemoteWebDriver

Here I am using the Chrome browser through RemoteWebDriver. I am using the RemoteWebDriver constructor RemoteWebDriver(remoteAddress, desiredCapabilities).
For the Argument remoteAddress I am passing a String parameter using URL constructor and using desiredCapabilities method capability.setCapability(String key, Object value);.
Argument Key is String parameter Capability name and Object is ChromeOptions.
And you can use several ChromeOptions methods


      public static void chromeDriverRemote(RemoteWebDriver driver) {  
           // create a ChromeOptions object  
           ChromeOptions options = new ChromeOptions();  
           // adding a extension to the chrome  
           options.addExtensions(new File("C:\\DRIVE\\My Documents\\Downloads\\AdBlock_v2.46.crx"));  
           // loading a profile to the chrome  
           options.addArguments("user-data-dir=C:\\Users\\sudas\\AppData\\Local\\Google\\Chrome\\User Data\\sudas");  
           // maximize chrome  
           options.addArguments("start-maximized");  
           // Create a DesiredCapabilities object  
           DesiredCapabilities capability = new DesiredCapabilities();  
           // Use the DesiredCapabilities method  
           capability.setBrowserName("chrome");  
           // use the DesiredCapabilities method capability.setCapability(String key, Object value);  
           capability.setCapability(ChromeOptions.CAPABILITY, options);  
           try {  
                // STEP 01  
                driver = new RemoteWebDriver(new URL("http://10.129.63.183:4444/wd/hub"), capability);  
           } catch (MalformedURLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  


Selenium using Forefox extension through RemoteWebDriver




Wednesday, January 13, 2016

Java System: Get Environment Map



  public static void getSystemEnvironmentMap() {
  Map envmap = System.getenv();
  Set> set = envmap.entrySet();
  Iterator> iterator = set.iterator();
  while (iterator.hasNext()) {

   Entry entry = iterator.next();
   System.out.println(entry.getKey());
   System.out.println(entry.getValue());
  }
 } 


This will return all environment variables




Selenium RemoteWebDriver usage

This is a write up about how to use RemoteWebDriver for all browsers

To start the server java -jar selenium-server-standalone-2.48.2.jar
When you start the server, chrome and firefox will work

Because the official documentation says

Client mode: where the language bindings connect to the remote instance. This is the way that the FirefoxDriver, OperaDriver and the RemoteWebDriver client normally work.

Server mode: where the language bindings are responsible for setting up the server, which the driver running in the browser can connect to. The ChromeDriver works in this way.

For internet Explorer and Chrome where language bindings are responsible for setting up the server start the server like



For Internet Explorer
C:\selenium>java -jar selenium-server-standalone-2.48.2.jar -Dwebdriver.ie.driver="C:\selenium\IEDriverServer_Win32_2.48.0\IEDriverServer.exe"

For Chrome
C:\selenium>java -jar selenium-server-standalone-2.48.2.jar -Dwebdriver.chrome.driver="C:\selenium\<path to chrome driver>

When you want to use multiple instance of same browser or multiple browser on same remote machine use GRID


Working with Internet Explorer 
_____________________________
Start the remote server using the following command

java -jar selenium-server-standalone-2.48.2.jar -Dwebdriver.ie.driver="C:\selenium\IEDriverServer_Win32_2.48.0\IEDriverServer.exe"

Below code will open ie browser at remote location  10.129.63.183:4444
desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);  
is used to ignoreProtectedModeSettings for several zones in IE.

      public static void ieRemoteWebDriver(RemoteWebDriver rwd) {  
       DesiredCapabilities desiredCapabilities = DesiredCapabilities.internetExplorer();  
       desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);  
       try {  
       rwd = new RemoteWebDriver(new URL("http://10.129.63.183:4444/wd/hub"), desiredCapabilities);  
       } catch (MalformedURLException e) {  
       // TODO Auto-generated catch block  
       e.printStackTrace();  
       }  
      }  


Below code will open ie browser at remote location  10.129.63.183:4444 
and will print browser details


      public static void ieRemoteWebDriver(RemoteWebDriver rwd) {  
           DesiredCapabilities desiredCapabilities = DesiredCapabilities.internetExplorer();  
           desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,  
                     true);  
           try {  
                rwd = new RemoteWebDriver(new URL("http://10.129.63.183:4444/wd/hub"), desiredCapabilities);  
                Capabilities actualCapabilityes = rwd.getCapabilities();  
                System.out.println(actualCapabilityes.getVersion());  
                System.out.println(actualCapabilityes.getBrowserName());  
                System.out.println(actualCapabilityes.getPlatform());  
           } catch (MalformedURLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  


For setting Capability for browser selection . Common for all browsers

KeyTypeDescription
browserNamestringThe name of the browser being used; should be one of {android|chrome|firefox|htmlunit|internet explorer|iPhone|iPad|opera|safari}.
versionstringThe browser version, or the empty string if unknown.
platformstringA key specifying which platform the browser should be running on. This value should be one of {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANDROID}. When requesting a new session, the client may specify ANY to indicate any available platform may be used. For more information see [GridPlatforms]

Setting desired capability for browser name

DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setBrowserName("internet explorer");
desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);

OR
   DesiredCapabilities desiredCapabilities = DesiredCapabilities.internetExplorer();  
           desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,  
                     true);  



Setting desired capability for Version, Platform (example)
desiredCapabilities.setCapability("platform", Platform.ANY);

desiredCapabilities.setCapability("version", "11");


  • For a list of capability specific to Internet Explorer please refer HERE




Working with Chrome Driver 
_____________________________

Start the server in remote machine

java -jar selenium-server-standalone-2.48.2.jar -Dwebdriver.chrome.driver="C:\selenium\chromedriver_win32\chromedriver.exe"



Selenium Chrome Driver Usage

Available constructors for Chrome Driver




A list of all Chrome Driver Capability

https://sites.google.com/a/chromium.org/chromedriver/capabilities

Chrome Driver usage for constructor ChromeDriver(service, options);

Opening a already created Chrome profile to a new Chrome browser instance.
To create a new chrome profile, enter chrome://version/ in chrome navigation bar and checkout the profilePath. Close the browser and rename the default profile path.

Now if you open the Chrome browser the browser will create a new default profile folder Default again
OR
you can use the below method and start an instance of Chrome browser by setting
options.addArgument("user-data-directory=C:/xx/xx/profile_name")

          // USE OF CHROME Driver constructor ChromeDriver(service, options)
 public static void ChromeLocalDriver02(WebDriver driver) {
  System.setProperty("webdriver.chrome.driver", "C:\\Java_Source_Code\\chromedriver_win32\\chromedriver.exe");
  // setting up the service
  ChromeDriverService.Builder builder = new ChromeDriverService.Builder();
  ChromeDriverService service = builder.withLogFile(new File("C:\\Test\\ie_log\\chrome1.log")).build();
  // chrome options
  ChromeOptions options = new ChromeOptions();
  // Opening Chrome browser with current default profile
  options.addArguments("user-data-dir=C:\\Users\\sudas\\AppData\\Local\\Google\\Chrome\\User Data\\sudas");
  // this is to start Chrome windows as maximized
  options.addArguments("start-maximized");
  driver = new ChromeDriver(service, options);
 } 
      }  


To find out which profile the browser is currently using enter chrome://version/ in Chrome's address bar and checkout the "ProfilePath"

Chrome Driver usage for constructor ChromeDriver(service, capabilities);


      // USE OF CHROME Driver CAPABILITY through DesiredCapabilities  
      // Used constructor ChromeDriver(service, capabilities)  
      public static void ChromeLocalDriver01(WebDriver driver) {  
           System.setProperty("webdriver.chrome.driver", "C:\\Java_Source_Code\\chromedriver_win32\\chromedriver.exe");  
           // "ChromeDriverService" similar to InternetExplorerDriverService  
           ChromeDriverService.Builder builder = new ChromeDriverService.Builder();  
           ChromeDriverService service = builder.withLogFile(new File("C:\\Test\\ie_log\\chrome1.log")).build();  
           DesiredCapabilities capabilities = new DesiredCapabilities();  
           // capabilities.setCapability(ChromeDriverService.CHROME_DRIVER_VERBOSE_LOG_PROPERTY,  
           // true);  
           capabilities.setCapability(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, true);  
           driver = new ChromeDriver(service, capabilities);  
      }  

Chrome Driver usage for constructor ChromeDriver(capabilities);

      public static void ChromeLocalDriver03(WebDriver driver) {  
           System.setProperty("webdriver.chrome.driver", "C:\\Java_Source_Code\\chromedriver_win32\\chromedriver.exe");  
           ChromeOptions options = new ChromeOptions();  
           options.addExtensions(new File("C:\\DRIVE\\My Documents\\Downloads\\AdBlock_v2.46.crx"));  
           DesiredCapabilities capabilities = new DesiredCapabilities();  
           capabilities.setCapability(ChromeOptions.CAPABILITY, options);  
           driver = new ChromeDriver(capabilities);  
      }  

Monday, January 11, 2016

Java Singletone class


For a singleton class it allows to create only one object of the class



 package singelton;  
 /***  
  * Steps to create a Singleton class Create a standard java class Create an  
  * instance of the same class like private static SingleTone instance = new SingleTone();  
  * create a private default constructor  
  * create a method and return the instance  
  *   
  * @author sudas  
  *  
  */  
 public class SingleTone {  
      public static void main(String[] args) {  
 SingleTone obj1 = SingleTone.singleInstance();  
 SingleTone obj2 = SingleTone.singleInstance();  
 System.out.println(obj1);  
 System.out.println(obj2);  
      }  
      private static SingleTone instance = new SingleTone();  
      private SingleTone() {  
           // TODO Auto-generated constructor stub  
      }  
      public static SingleTone singleInstance() {  
           return instance;  
      }  
 }  

When you run this you will see both the objects (obj1 and obj2) are pointing to the same memory on hip, so basically obj1 and obj2 both are same objects of class Singleton


 singelton.SingleTone@2a139a55  
 singelton.SingleTone@2a139a55  

Saturday, January 9, 2016

Selenium: WebDriverEventListener and EventFiringWebDriver

WebDriverEvenListner interface and EventFiringWebDriver class


When you are running test using WebDriver Interface in Selenium there are many events that get fired before and after navigation to an URL.

EventFiringWebDriver class is a wrapper for normal WebDriver interface, that gives the capability to WebDriver to fire Events. EventListener class (let’s say) which implements WebDriverEventListner handles all the events that are dispatched by EventFiringWebDriver class

To capture even there are two different type of implementations
  1. By creating a class say EventListner implements WebDriverEventListner
OR

    2. By creating a class say EventListner extends AbstractWebDriverEventListner


class EventListner implements WebDriverEventListener
{
@Overriding method 
   ////////// NAVIGATION RELATED METHODS ////////////////
   /////////////////// FINDBY RELATED METHODS ///////////////
   //////////////////// CLICKON RELATED METHODS ///////////////
   ///////////////// CHANGE OF VALUE RELATED METHODS //////////////
   /////////////// SCRIPT EXECUTION RELATED METHODS ///////////////
   /////////////// EXCEPTION RELATED METHODS ///////////////////////


}



/***
* Step -02 Register the WebDriverEventListner (Listener) with the WebDriver
* instance. 1. Create WebDriver instance 2. Create EventFiringWebDriver
* instance and pass the WebDriver object to EventFiringWebDriver
* constructor argument. 3. Create an instance of EventListener.
* EventListner class created at step-01 4. Register the listener i.e
* EventFiringWebDriver efwd = new EventFiringWebDriver(driver)
* efwd.register(object of EventListner)
*/


public static void registerListener(WebDriver driver) {
// 1. Create WebDriver instance
driver = new ChromeDriver();

// * 2. Create EventFiringWebDriver instance and pass the WebDriver
// object to EventFiringWebDriver constructor argument.
EventFiringWebDriver efwd = new EventFiringWebDriver(driver);

// * 3. Create an instance of EventListener. EventListner class created
// at step-01
EventListner listner = new EventListner();

// * 4. Register the listener
efwd.register(listner);

}

Friday, January 8, 2016

Selenium Internet Explorer Driver usage

Available Constructors for InternetExplorerDriver




  • Use of internet explorer constructor "InternetExplorerDriver(capabilities)"



   // using Internet Explorer local through Internet Explorer Driver  
      public static void ieLocalDriver(WebDriver driver) {  
           System.setProperty("webdriver.ie.driver",  
                     "C:\\Java_Source_Code\\IEDriverServer_Win32_2.48.0\\IEDriverServer.exe");  
           DesiredCapabilities capabilities = new DesiredCapabilities();  
           // setting IE specific capability  
           // this is to override Protected mode settings for zones  
           capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);  
           // this is for setting logging  
           capabilities.setCapability(InternetExplorerDriver.LOG_FILE, "C:\\Test\\ie_log\\logs.log");  
           // this is for setting logging level  
           capabilities.setCapability("logLevel", "INFO");  
           driver = new InternetExplorerDriver(capabilities);  
  
      }  


  • Use of  set capability

capability can be either set through InternetExplorerDriver class static fields OR can be set through static final fields from CapabilityType Interface.


  • Using InternetExplorerDriver constructor  "InternetExplorerDriver(service, capabilities)"


      public static void ieLocalDriver02(WebDriver driver) {  
           System.setProperty("webdriver.ie.driver",  
                     "C:\\Java_Source_Code\\IEDriverServer_Win32_2.48.0\\IEDriverServer.exe");  
           // this is to override Protected mode settings for zones  
           DesiredCapabilities capabilities = new DesiredCapabilities();  
           capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);  
           InternetExplorerDriverService.Builder builder = new InternetExplorerDriverService.Builder();  
           InternetExplorerDriverService service = builder.withLogFile(new File("C:\\Test\\ie_log\\ie.log"))  
                     .withLogLevel(InternetExplorerDriverLogLevel.INFO).build();  
           // I am using the capability and service both  
           driver = new InternetExplorerDriver(service, capabilities);  
      }  


Internet Explorer specific capability 
https://code.google.com/p/selenium/wiki/DesiredCapabilities

This is how the capability constructor are used



For setting up the capability of a browser either you use STATIC FINAL VALUES of 
InternetExplorerDriver



OR 
pass it as a String parameter to capabilities.setCapability(String, String value), etc

Other Internet Explorer Capabilities


   

Thursday, January 7, 2016

TestNG printing data provider parameter to report and Reporter Interface



Test NG. Use of Reporter.Log, Data Provider, Getting the data provider parameter on reports




      @DataProvider(name = "dp")  
      public String[][] dp() {  
           String testCaseName[][] = { { "T_Name01"},{"T_Name02" }};  
           return testCaseName;  
      }  
      String testCaseNamePrint = "Test_Case_01";  
      WebDriver driver;  
      @Test(enabled = true, dataProvider = "dp", dataProviderClass = sudas.com.se.study.SandBoxTest.class)  
      public void testCase01(String testCaseNamePrint) {  
           driver.navigate().to("http://www.google.co.in");  
 Reporter.log("This is my Test", true);

      }  
      @Test  
      public void testCase02() {  
           System.out.println("Test Case 02");  
      }  
      @Test  
      public void testCase03() {  
           System.out.println("Test Case 03");  
      }  
      @Test  
      public void testCase04() {  
           System.out.println("Test Case 04");  
      }  
      @BeforeMethod  
      public void beforeMethod() {  
           System.out.println("@BeforeMethod");  
      }  
      @AfterMethod  
      public void afterMethod() {  
           System.out.println("@AfterMethod");  
      }  
      @BeforeClass  
      public void beforeClass() {  
           System.out.println("@BeforeClass");  
      }  
      @AfterClass  
      public void afterClass() {  
           System.out.println("@AfterClass");  
      }  
      @BeforeTest  
      public void beforeTest() {  
           System.out.println("@BeforeTest");  
      }  
      @AfterTest  
      public void afterTest() {  
           System.out.println("@AfterTest");  
      }  
      @BeforeSuite  
      public void beforeSuite() {  
           System.out.println("@BeforeSuite");  
           driver = new FirefoxDriver();  
      }  
      @AfterSuite  
      public void afterSuite() {  
           System.out.println("@AfterSuite");  
      }  

Selenium ScreenShots


Working with screen shots/ Print screen through selenium API

      public static String takeScreenShots(WebDriver driver) {  
           TakesScreenshot screen = (TakesScreenshot) driver;  
           File srcFile = screen.getScreenshotAs(OutputType.FILE);  
           copyFile(srcFile, "C:\\Test\\fileCopy");  
           driver.get("http://www.google.com");  
           String title = driver.getTitle();  
           return title;  
      }  
      public static void copyFile(File srcFile, String directoryPath) {  
           try {  
                // srcFile = new File("C:\\Test\\File1.txt");  
                File desDirectory = new File(directoryPath);  
                FileUtils.copyFileToDirectory(srcFile, desDirectory);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  

Wednesday, January 6, 2016

FireFox ProfileManager

Windows

firefox.exe -ProfileManager \\ or firefox.exe -p


Mac

/Applications/Firefox.app/Contents/MacOS/firefox -profilemanager


Linux

./firefox -profilemanager

Selenium handling cookies



Retrieving cookie from website


 public class CookieExample {  
      static WebDriver driver;  
      static String webAddress = "http://xxxxxxxx:8080/xxxx/shared/config/config.jsp";  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           System.setProperty("webdriver.chrome.driver", "C:\\Java_Source_Code\\chromedriver_win32\\chromedriver.exe");  
           driver = new ChromeDriver();  
           Iterator<Cookie> cookies = login(driver, webAddress, null, "arsystem");  
           while (cookies.hasNext()) {  
 Cookie cookie = cookies.next();  
 System.out.println(cookie.getDomain());  
 System.out.println(cookie.getName());  
 System.out.println(cookie.getPath());  
 System.out.println(cookie.getExpiry());  
 System.out.println(cookie.getValue());  
 System.out.println(cookie.isSecure());  
           }  
           driver.close();  
      }  
      public static Iterator<Cookie> login(WebDriver driver, String webAddress, String loginID, String password) {  
           driver.get(webAddress);  
           driver.findElement(By.name("password")).clear();  
           driver.findElement(By.name("password")).sendKeys(password);  
           driver.findElement(By.className("button")).click();  
           new WebDriverWait(driver, 10)  
                     .until(ExpectedConditions.elementToBeClickable(driver.findElement(By.name("Logout"))));  
           driver.findElement(By.name("Logout")).click();  
           Set<Cookie> cookies = driver.manage().getCookies();  
           Iterator<Cookie> cookiesIterator = cookies.iterator();  
           return cookiesIterator;  
      }  
 }  

Selenium - FireFox Driver Usage

Use of FireFox Profile

Available constructors

Here we will see how Firefox driver can make use of a already created profile in firefox.
To check out which profile Firefox is using currently  enter about:support in Firefox address bar and check for "Profile Folder".

To create / modify/ delete a new Firefox profile 



To create, rename, or delete a profile, you have to perform the following steps:

1. Open the Firefox profile manager. To do that, in the command prompt

terminal, you have to navigate to the install directory of Firefox; typically, it

would in Program Files if you are on Windows. Navigate to the location where
you can find the firefox.exe file, and execute the following command:
firefox.exe -p
It will open the profile manager that will look like the following screenshot:
Note that before executing the above command, you need to make sure you
close all your currently running Firefox instances.
2. Use the Create Profile... button to create another profile, Rename Profile...
button to rename an existing profile, and Delete Profile... button to delete one.



Firefox Profile :
Firefox profile has a default constructor and other constructor taken an argument of type file.

Use of constructor FirefoxDriver(FirefoxProfile profile)

// using a already created profile

public static void fireFoxProfileA(WebDriver driver) { FirefoxProfile profile = new FirefoxProfile( new File("C:\\Users\\sudas\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\t1skcchd.sudas1")); driver = new FirefoxDriver(profile); driver.get("http://www.yahoo.com"); }

// Creating an instance of firefox profile for a specific plugin and store as JSON

public static void fireFoxProfileB(WebDriver driver) { FirefoxProfile profile = new FirefoxProfile(); try {  
// adding a extension to the new Firefox session
                profile.addExtension(new File("C:\\Java_Source_Code\\FireFoxExtensions\\firebug-2.0.13-fx.xpi"));  
                String json = profile.toJson();  
                // write the profile to a file  
                BufferedOutputStream bos = new BufferedOutputStream(  
                          new FileOutputStream(new File("C:\\Java_Source_Code\\FireFoxExtensions\\profile.json")));  
                bos.write(json.getBytes());  
   
                driver = new FirefoxDriver(profile);  
                driver.get("http://www.yahoo.com");  
                bos.flush();  
                bos.close();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  



Use of preference with Firefox 

FirefoxDriver overwrites all the default preferences of Firefox in the user.js file
for you

List of preference
user_pref("extensions.update.notifyUser", false);
user_pref("security.warn_entering_secure.show_once", false);
user_pref("devtools.errorconsole.enabled", true);
user_pref("extensions.update.enabled", false);
user_pref("browser.dom.window.dump.enabled", true);
user_pref("offline-apps.allow_by_default", true);
user_pref("dom.disable_open_during_load", false);
user_pref("extensions.blocklist.enabled", false);
user_pref("browser.startup.page", 0);
user_pref("toolkit.telemetry.rejected", true);
user_pref("prompts.tab_modal.enabled", false);
user_pref("app.update.enabled", false);
user_pref("app.update.auto", false);
user_pref("toolkit.networkmanager.disable", true);
user_pref("browser.startup.homepage", "about:blank");
user_pref("network.manage-offline-status", false);
user_pref("browser.search.update", false);
user_pref("toolkit.telemetry.enabled", false);
user_pref("browser.link.open_newwindow", 2);
user_pref("browser.EULA.override", true);
user_pref("extensions.autoDisableScopes", 10);
user_pref("browser.EULA.3.accepted", true);
user_pref("security.warn_entering_weak", false);
user_pref("toolkit.telemetry.prompted", 2);
user_pref("browser.safebrowsing.enabled", false);
user_pref("security.warn_entering_secure", false);
user_pref("security.warn_leaving_secure.show_once", false);
user_pref("webdriver_accept_untrusted_certs", true);
user_pref("browser.download.manager.showWhenStarting", false);
user_pref("dom.max_script_run_time", 30);
user_pref("javascript.options.showInConsole", true);
user_pref("network.http.max-connections-per-server", 10);
user_pref("network.http.phishy-userpass-length", 255);
user_pref("extensions.logging.enabled", true);
user_pref("security.warn_leaving_secure", false);
user_pref("browser.offline", false);
user_pref("browser.link.open_external", 2);
user_pref("signon.rememberSignons", false);
user_pref("webdriver_enable_native_events", true);
user_pref("browser.tabs.warnOnClose", false);
user_pref("security.fileuri.origin_policy", 3);
user_pref("security.fileuri.strict_origin_policy", false);
user_pref("webdriver_assume_untrusted_issuer", true);
user_pref("startup.homepage_welcome_url", "");
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("security.warn_submit_insecure", false);
user_pref("webdriver_firefox_port", 7055);
user_pref("dom.report_all_js_exceptions", true);
user_pref("security.warn_viewing_mixed", false);
user_pref("browser.sessionstore.resume_from_crash", false);
user_pref("browser.tabs.warnOnOpen", false);
user_pref("security.warn_viewing_mixed.show_once", false);
user_pref("security.warn_entering_weak.show_once", false);

To set the preference use the Key, Value pair
Use FireFox profile with preference

Firefox profile methods

Here I am using an already existing profile and setting a preference on the profile

      // using firefox profile along with preference   
      public static void fireFoxProfileA(WebDriver driver) {  
           FirefoxProfile profile = new FirefoxProfile(  
                     new File("C:\\Users\\sudas\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\t1skcchd.sudas1"));  
           //setting preference   
           profile.setPreference("browser.startup.homepage", "https://www.yahoo.co.in/");  
           driver = new FirefoxDriver(profile);  
 //          driver.get("http://www.yahoo.com");  
      }  

Monday, January 4, 2016

Selenium - WebDriver Wait




Implicit wait and Explicit wait

  public static void wait01(WebDriver driver) {  
           WebElement element = driver.findElement(By.name(""));  
           // implicit wait  
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
           // explicit wait  
           WebDriverWait explicitwait = new WebDriverWait(driver, 10);  
           explicitwait.until(ExpectedConditions.elementToBeClickable(element));  
      }  

Fluent Wait
      public static void wait02(WebDriver driver) {  
           // fluent wait  
           org.openqa.selenium.support.ui.Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)  
                     .withTimeout(10, TimeUnit.SECONDS)  
                     .pollingEvery(3, TimeUnit.SECONDS);  
           wait.until(new Function<WebDriver, WebElement>() {  
                @Override  
                public WebElement apply(WebDriver driver) {  
                     // TODO Auto-generated method stub  
                     return driver.findElement(By.name(""));  
                }  
           });  
      }