Monday, 18 April 2016

Selenium Question

-          Assume, given web application contains 10 dynamic text boxes.
-          Text box placing/location will also changes dynamically.
-          Now we need to key in text in one specific text box, which does not contain any unique locator ( We are not able to find out uniqueness with partial text too )

How you do you achieve this?                                                  

Analysis:
-          No unique ID , tool tip, value, css style, etc.
-          We are not able to draw unique ness with partial ID / text / value / etc

Tip:
-          Only one control is having unique ID and whose position is dynamic.
      

  Idea:
-          Can we use below Xpath selectors


AxisName
Result
ancestor
Selects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-self
Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself
attribute
Selects all attributes of the current node
child
Selects all children of the current node
descendant
Selects all descendants (children, grandchildren, etc.) of the current node
descendant-or-self
Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself
following
Selects everything in the document after the closing tag of the current node
following-sibling
Selects all siblings after the current node
namespace
Selects all namespace nodes of the current node
parent
Selects the parent of the current node
preceding
Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes
preceding-sibling
Selects all siblings before the current node
self
Selects the current node


Examples:

Example
Result
child::book
Selects all book nodes that are children of the current node
attribute::lang
Selects the lang attribute of the current node
child::*
Selects all element children of the current node
attribute::*
Selects all attributes of the current node
child::text()
Selects all text node children of the current node
child::node()
Selects all children of the current node
descendant::book
Selects all book descendants of the current node
ancestor::book
Selects all book ancestors of the current node
ancestor-or-self::book
Selects all book ancestors of the current node - and the current as well if it is a book node
child::*/child::price
Selects all price grandchildren of the current node




Examples:


//td[text() = ' Color Digest ']/following-sibling::td[2]
//h2[contains(text(),'Hello')]/parent::div//div[//a[text()='SELENIUM']]/following-sibling::div[@class='rt-grid-2']

Selenium Question


-          Assume, given web application is accessible in one Machine ( IP : 10.10.10.10)
-          You need to write selenium tests and run.
-          You are not allowed to install / download any software except browser in IP: 10.10.10.10.
How you do you achieve this?                                                 
Analysis:
-          We can start coding in our local laptop , later we can think about executing tests.
-          To find out locators ( xpaths / css / etc) , connect to the machine IP 10.10.10.10 via remote desktop and fetch as much info as needed.
Now Execution part,
-          When we execute our test in local, tests should run in the IP 10.10.10.10.
-          This can be achieved via selenium GRID.
-          Create a node in IP 10.10.10.10 and connect to a HUB ( either in your laptop / IP 10.10.10.10)
-          Write Remote web driver code instead of plain webdriver.

Just hit run. That’s all.

Selenium Grid (Advanced)

Selenium Grid distributes our tests across multiple machines so that we can run them in parallel, cutting down the time required for running tests.

The selenium-server-standalone package includes the Hub, WebDriver, and Selenium RC .

Setting up Hub: (Simple)
java -jar selenium-server-standalone-2.53.0.jar -port 4444 -role hub

Setting up Node:(Simple)
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -hub http://xx.xx.xx.xx:4444/grid/register –port 8989

Setting up Node:(Complex)
If you want to setup a node with only IE browsers

Option1: via Command Text
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -browser "browserName=internet explorer,version=11,maxinstance=1,platform=WINDOWS" -hub http://xx.xx.xx.xx:4444/grid/register –port 8989

Option2: via Json file

Save below Json as selenium-node-win-ie11-cfg.json

{
           "class": "org.openqa.grid.common.RegistrationRequest",

           "capabilities":
                              [
                                 { "seleniumProtocol": "WebDriver", 
                                    "browserName": "internet explorer",
                                    "version": "11",
                                    "maxInstances": 1,
                                    "platform" : "WINDOWS"
                                 }
                              ],

          "configuration":
                      {
                           "port": 8989,
                           "register": true,
                           "host": "xx.xx.xx.100", 
                           "proxy": "org.openqa.grid.selenium.proxy. DefaultRemoteProxy", 
                           "maxSession": 2,
                          "hubHost": "xx.xx.xx.100",
                          "role": "webdriver",
                          "registerCycle": 5000,
                          "hub": "http://xx.xx.xx.100:4444/grid/register",
                          "hubPort": 4444,
                          "remoteHost": "http://xx.xx.xx.101:8989"
                       }
}


one more json:


{
  "capabilities":
      [
        {
          "browserName": "chrome",
          "maxInstances": 5
        },
        {
          "browserName": "firefox",
          "maxInstances": 5
        },
        {
          "browserName": "internet explorer",
          "maxInstances": 5
        },
        {
          "browserName": "safari",
          "maxInstances": 5
        }
      ],
    "configuration":
        {
"_comment": "Configuration for Node",
        "nodeTimeout":120,
        "port":5555,
        "hubPort":4444,
        "hubHost":"hubIpAddress",
        "nodePolling":2000,
        "registerCycle":10000,
        "register":true,
        "cleanUpCycle":2000,
        "timeout":30000,
        "maxSession":5,
        }
}


Command Text:

java -jar selenium-server-standalone-53.jar -role webdriver -nodeConfig selenium-node-win-ie11-cfg.json


Selenium Remote WebDriver code:

DesiredCapabilities cap = new DesiredCapabilities();  
                                cap.setBrowserName("firefox");
                                cap.setPlatform(org.openqa.selenium.Platform.WINDOWS);


WebDriver driver = new RemoteWebDriver(new URL("http://xx.xx.xx.xx:4444/wd/hub"),cap);



Suite.
xml:

<suite name="Parallel Tests" verbose="1" thread-count="4"
parallel="tests">

</suite>

thread-count=“4” describes the maximum number of threads to be executed in parallel.


---------------------------------------------------------------------------------------------------------------------------------

Each node contains  
5 Chrome, 5 Firefox and 1 IE browser under Browser section like below.




Do you want only one IE browser?

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore




You want one browser per each type?

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
-browser browserName=firefox -browser browserName=chrome




maxInstances:

maxInstance is used to limit the number of browser initialization in a node.
For example if you want to work with 2 Firefox and 2 IE then you can start the node using maxInstance.
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub 
http://localhost:4444/grid/register -port 5556 -browser browserName=firefox,maxInstance=3


maxSession:
maxSession is used to configure how many number of browsers can be used parallel in the remote system.
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub http://localhost:4444/grid/register -port 5556 -browser browserName=chrome,maxInstance=3 -browser browserName=firefox,maxInstance=3 –maxSession 3



Selenium Grid ( Simple )

Selenium Grid distributes our tests across multiple machines so that we can run them in parallel, cutting down the time required for running tests.

The selenium-server-standalone package includes the Hub, WebDriver, and Selenium RC needed to run the grid.

Setting up Hub: (Simple)
java -jar selenium-server-standalone-2.53.0.jar -port 4444 -role hub

Setting up Node:(Simple)
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -hub http://xx.xx.xx.xx:4444/grid/register –port 8989 -Dwebdriver.chrome.driver=path/to/chromedriver.exe


Selenium Remote WebDriver code:

DesiredCapabilities cap = new DesiredCapabilities(); 
                                cap.setBrowserName("firefox");
                                cap.setPlatform(org.openqa.selenium.Platform.WINDOWS);


WebDriver driver = new RemoteWebDriver(new URL("http://xx.xx.xx.xx:4444/wd/hub"),cap);


Thats all.

Design Patterns : singleton / Single Object class


Here is the simple definition.

Single Object class have its constructor as private and have a static instance of itself.

Explanation:

1. Private constructor:  This stops us creating object for the class, Not even one object creation is allowed.

But, we want one object.
How can we create it?

2. Static instance of itself: Create a instance of self and mark it as static.

'Static' help us to access the instance with out creating object ( Anyways with the point#1, we can not create instance )


public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
    
}

// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

 

Friday, 15 April 2016

Logical Qn : Assume that you have 25 horses, and you want to pick the fastest 3 horses out of those 25. In each race, only 5 horses can run at the same time because there are only 5 tracks. What is the minimum number of races required to find the 3 fastest horses without using a stopwatch?



After analyzing a bit, Here are the pointers.
- We need to put all the horses into a race ( 5 at a time ) to find out the best 3 performers.
- Maximum 5 Horses in a race, so 5 times we need to conduct.
- After 5 Races, below is the table we can draw "ORDER by best performer"

Race1H1  -  Race2H6 -  Race3H11 -  Race4H16 -  Race5H21
Race1H2  -  Race2H7 -  Race3H12 -  Race4H17 -  Race5H22
Race1H3  -  Race2H8 -  Race3H13 -  Race4H18 -  Race5H23
Race1H4  -  Race2H9 -  Race3H14 -  Race4H19 -  Race5H24
Race1H5  -  Race2H10 -Race3H15 -  Race4H20 -  Race5H25

Our Aim is to find the best three performers. so, we can eliminate last two rows.
Reason: We are least bothered about 4th and 5th best in each race.
They can not be one among top three performers.

Our Target table is

Race1H1  -  Race2H6 -  Race3H11 -  Race4H16 -  Race5H21
Race1H2  -  Race2H7 -  Race3H12 -  Race4H17 -  Race5H22
Race1H3  -  Race2H8 -  Race3H13 -  Race4H18 -  Race5H23

Now Race # 6: all top players in each race:
i.e
Race1H1  -  Race2H6 -  Race3H11 -  Race4H16 -  Race5H21

Assume results are, 1st place Race1H1  ; 2nd place Race2H6 ; 3rd place Race3H11


Now Race # 7: will gives the 2nd and 3rd place horse.
i.e we need to conduct a race with below set.
                 -  Race2H6 -  Race3H11
Race1H2  -  Race2H7
Race1H3

why we eliminated other horses?

Elimination Set # 1
Race4H16 -  Race5H21
Race4H17 -  Race5H22
Race4H18 -  Race5H23

Reason: As 3rd best horse is Race3H11. so, above set is definitely is not in 1,2,3 positions.

Elimination Set # 2
Race3H12
Race3H13

Reason: same as above.

Elimination Set # 3
Race2H8

Reason: as Race1H1 is 1st , there may be chance for 2nd is Race1H2 or Race2H6
chance for 3rd is Race1H3, Race2H6, Race2H7, Race3H11
but not Race2H8

so, Answer is 7



-

Thursday, 4 December 2014

Integrating AutoIt with Selenium


What is AutoIt:

       AutoIt is freeware scripting language for automating the windows GUI.

      
Why is AutoIt:
       When you start working with web-application so many time you will get window based pop-up like- file upload, download pop up, window authentication etc. In this case Selenium fails and will not be able to handle desktop elements to avoid this we will use AutiIt script that will handle desktop or windows elements and will combine AutoIt script with our Selenium code.

Setup / Configuration:
Download and Install AutoIt software and Editor here



Install the software.

IMAGE 2:

Search for “sciTE Script Editor” or “SciTE.exe” in RUN dialog.


Problem statement:

Automate file upload feature in http://www.dropzonejs.com/

We know how to write selenium code until we click upload button and here is the code.

public static void main(String[] args) throws InterruptedException, IOException {
             
              String baseUrl = "http://www.dropzonejs.com/";
              driver = new FirefoxDriver();
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.get(baseUrl);
              driver.manage().window().maximize();
              Thread.sleep(6000);             
              driver.findElement(By.id("demo-upload")).click();
              Thread.sleep(3000);
       }

Now, we need to select a file from windows explorer and Selenium cannot do it for obvious reasons.

But, we can achieve this using AutoIt.

Here is the AutoIt script:

; Wait 10 seconds for the Upload window to appear
  WinWait("[CLASS:#32770]","",10)

; Set input focus to the edit control of Upload window using the handle returned by WinWait
  ControlFocus("File Upload","","Edit1")
  Sleep(2000)

; Set the File name text on the Edit field
  ControlSetText("File Upload","","Edit1","C:\Users\testUser\Downloads\A.jpg")
  Sleep(2000)

; Click on the Open button
  ControlClick("File Upload", "","Button1");


Explanation:
WinWait pauses execution of the script until the requested window existed
Now, we need to understand how to locate the file upload windows explorer.
Open      Au3Info.exe (Window Info tool), select Finder tool and point to file upload windows explorer to locate it.

We have two parts in ‘Window Info tool’, one is ‘Basic window Info’ and other is ‘Basic Control Info’.

As we are dealing with windows explorer wait, lets concentrate on ‘Basic window info’, notice about CLASS id to locate the window as ([CLASS:#32770])

Similarly we can locate each and every windows explorer element.

Few Methods to remember:

ControlFocus Sets input focus to a given control on a window.
ControlSetText Sets text of a control.
ControlClick  Sends mouse click command to a given control.

SAVE the file:

Save AutoIt script file as with ‘.au3’ extension.  Ex: one.au3


Compiling au3 script file:

Right click on one.au3 file and select compile script option.
A new file named one.exe will be generated.

Integrating AutoIt

with Selenium:

public static void main(String[] args) throws InterruptedException, IOException {
             
              String baseUrl = "http://www.dropzonejs.com/";

              driver = new FirefoxDriver();
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.get(baseUrl);
              driver.manage().window().maximize();
              Thread.sleep(6000);
             
              driver.findElement(By.id("demo-upload")).click();
              Thread.sleep(3000);
             
              Runtime.getRuntime().exec("E:/one.exe");       

       }     


Just run the script, that’s all.


NOTE: We do not need to add any jars to the project for this to run.