Thursday, March 17, 2016

Selenium : How to Create Xpath


Selenium : How to Create Xpath

Target URL: www.mouthshut.com
Target Web element: Signup button, Login Button
Tools used:
·         FireBug : To formulate Xpath
·         Selenium Ide : To Test the formulated Xpath
Things to remember:-
1.       Target page should be open is FireFox
2.       Selenium ide and Firebug  should be open
3.       The formulated Xpath will go into “Target” field of Selenium IDE.
4.       All Xpath which go into IDE start with “xpath=//”
5.       The page usually start with <body> , therefore the foremost parent will always be “//Body” while writing Full Path
6.       Html Page may be like :
<body id=”aaaaa”>

   <div id=”bbbbb”>

   <div id=”cccc”>

          <a id=”dddd” class=”1111”>

          <ul id=”eeee”  target=”2222” href=”5555”>

  <div id=”ffff”>
               
Syntax in IDE:
Xpath=//branch/branch [ @property=’value’ or contains ( @property, “value”) ]
In the above example :
1.   Branch or Nodebody , div , a , ul ,img
Note : Each Node value will have  many properties and many values .Therefore always start with a node value or "*" along with its relate property and value (Ex ://a[@target='_new']  or //*[@target='_new']  )
2.   Propertyid , class , target
3.   Valueaaaa , bbbb , cccc , dddd , 1111 , 2222 , eeee , ffff ,5555

Syntax in Selenium (Eclipse Java) 
   ( Note -"Syntax in Selenium IDE" is only used to create Xpath and the below syntax is the usage of Xpath created using IDE )
Syntax :
WebElement oObject_Name=Driver_Object.findElement(By.xpath("Created Xpath Goes here ,starting from '//'"));
Example : 
oDriver=new FirefoxDriver();
oDriver.get("https://URL_Here");
WebElement oObject=oDriver.findElement(By.xpath("//branch/branch [ @property=’value’ or contains ( @property, “value”) ]"));

1.     Using Full Path
 xpath=//body/form/div[7]/div/div[2]/div/div[2]/ul/li/a
(The page usually start with <body> , therefore the foremost parent will always be “//Body” while writing Full Path )
Selenium Code :
 oDriver=new FirefoxDriver();
oDriver.get("https://www.mouthshut.com");
oTitle=oDriver.findElement(By.xpath("//body/form/div[7]/div/div[2]/div/div[2]/ul/li/a"));
2.     Using Last()
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a
3.     Using Full Path+ @ attribute
·         xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a[@class='']
·         xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a[@style='background-color: transparent;']
(For Login Button)
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li[2]/a[@target='_new']
4.      Using only @ attribute      (For Login Button)
xpath=//a[@target='_new']
(Which is equivalent to
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li[2]/a[@target='_new']    )
5.     Using Descendants
xpath=//div[@class='new-menu']/descendant::div[@class='fr']
6.     Using keywords
xpath=//a[contains(@href, "javascript:__doPostBack(")]
xpath=//a[contains(@id, "ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUp")]



7.     And Operation
xpath=//a[contains(@id, "ctl00") and contains(@href,"javascript:_")]


8.     using position()
xpath=//div[@class='tdltaln']/div[position()=2]/ul/li


9.     Using starts-with keyword
xpath=//a[starts-with(@href, "https://graph.facebook.com")]
10. OR (|) condition
xpath=//a[@id='ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUpLink' or contains(@href,"javascript:__doPostBack")]

 xpath=//a[contains(@id,"ctl00_ctl00_ctl00_") or contains(@href,"javascript:__doPostBack") ]


 xpath=//a[contains(@href,"javascript:__doPostBack") or contains(@id,"ctl00_ctl00_ctl00_")]

11. Going 1 step back  
     Traversing from child to parent use    "/.."
12. Going back multiple steps or reverse tracing ( ancestor:: )
Ex :If user "ancestor::div" , then all the ancestor elements are highlighted with "div" node

 Back Trace to first occurrence of div element 
 //*[text()='Biological Sciences']/ancestor::div[1]
13. Going to specfic child element from parent node:( child:: )
Simialr to just "/ut[1]"
//*[text()='Biological Sciences']/ancestor::div[1]/child::ul[1]
 
14. Wild Card “*”
xpath=//*[@id="ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUpLink"]
15. Nth element
xpath=//ul[@class='login']/*[1]


16. No child
xpath=//img[count(*)=0]  

17. Last Second or Last But one 
xpath=//div[@class='dvaligncenter']/div[last()-1]//a

Examples for Xpath
xpath=xpathExpression: Locate an element using an XPath expression.

1. xpath=//img[@alt='The image alt text']
2. xpath=//table[@id='table1']//tr[4]/td[2]
3. xpath=//a[contains(@href,'#id1')]
4. xpath=//a[contains(@href,'#id1')]/@class
5. xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
6. xpath=//input[@name='name2' and @value='yes']
7. xpath=//*[text()="right"]
8. xpath=//*[@id='view']/*[not(@selected='selected')][1]
9. xpath=//*[text()='Biological Sciences']/ancestor::div[1]
10. xpath=.//*[local-name(.)='th' or local-name(.)='td']
Xpath summary
1.Path
    1. Full
    2. Full+attribute
    3. Attribute
    4. Wild Card(*)
    5. Recent ancestor "/.. "
    6. //a[6]
    7. div[3][contains(@id,'dvheader')] -goto 3rd element and fetch if it has dvheader similar to AND
    2.Functions
    1.  position
    1. [Last()]  //[Last[]-1]
    2. [Position()= 42]
    3. count
    1. text
    1. [starts-with(@,””)] -- Used For Dynamic Elements
    2. [contains(@,””)] -- Used For Dynamic Elements
    3. [text()=””] --text
    3.Logical
    1. And
    2. or
    3. not


  1. Navigation
  2.  Descendants::div[1]



  3. ancestor::div[1]
  4. child::div[1]

                   
    Ref:
                    http://software-testing-tutorials-automation.blogspot.in/2013/06/xpath-tutorials-identifying-xpath-for.html

    Wednesday, March 16, 2016

    Gradle : Debugging Gradle Project

    Gradle : Debugging Gradle Project



    Since my last Analysis I found fairly less information on Debugging Gradle in my line of work which is specifically on Automation .

    So the most convenient way was Debug using TestNG rather than Gradle .As I prefer using TestNg as my Automation Framework over Junit so there will be Testng.xml in the project folder (or similar xml file ).


    One can directly Start debugging  by :Rt ck on testng.xml > Debug As >TestNg


    If you are getting any error make sure you do these.Assuming you are using Eclispe
    1. Make sure you have plugin TestNg installed to eclipse .If not then goto Help>Market Place>Enter "testng" and search.
    2. Select testNG for Eclipse and click on Install >Select all options > restart Eclipse after installing
    3. goto  Project (title bar) > Clean
    4. Rt ck on Project > Properties >Java Build Path>Add Library > Select TestNG >Ck on OK

    Now user should be able to Debug for Gradle projects using Testng as well using Rt ck on testng.xml > Debug As >TestNg .



    Java : Introduction to Guava Core Libaray

    Java : Introduction to Guava Core Library

    download Jar :http://mvnrepository.com/artifact/com.google.guava/guava

    http://docs.guava-libraries.googlecode.com/git/javadoc/overview-summary.html
    (Visit the above JavaDoc for more information  and usage . click on Frames to view complete classes)




     What Is Guava ?


    -    Open Source libraries provided by Google
    -    provides utility methods

    Most Frequently Used Classes

    1. Optional - facilitate the code to handle values as available or not available instead of checking null values.
    2. Preconditions - provide static methods to check that a method or a constructor is invoked with proper parameters.
    3. Ordering - multiple utility methods, multi-type sorting capability, etc
    4. Objects - provides helper functions applicable to all objects such as equals, hashCode, etc.
    5. Range - represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range.
    6. Throwables - Static class provides utility methods related to Throwable interface.
    7. Collections Utilities - Provides utility api for handling ArrayLists,Lists,Maps,Sets etc .,
    8. String Utilities - Provides utility api for Strings.(Splitter ,Joiner, CaseFormats etc., are one of them)
    9. Math Utilities - For performing Mathoperations

    Tuesday, March 15, 2016

    Java : Exceptions (try catch)


    Java : Exceptions (try catch)



    1. Creating and Catching an Exception
        public void crossFingers()
        (
            try{
                Object.takeRisk();
            ) catch (BadException ex) // "ex" can be any variable
                System. out.println ("Aaarqh! ") ;
                ex .printStackTrace () ;
            }
        }

        public void takeRisk () throws BadException {
            if (abandonAllHope) {
                throw new BadException();
            }
        }

    ---------------------
    2. A finally block - runs regardless of an exception or even if the catch has a return statement
       
        try (
            turnOvenOn();
            x.bake () ;
        }catch (BakingException ex)
            ex.printStackTrace();
        }finally { //
    runs regardless of an exception or even if the catch has a return statement        
    turnOvenOff();
        }

       
    3. Multiple try catch

        try {
            throw new IOException();
            }catch (FileNotFoundException f){
               
            }catch (IOException  e){
                System.out.println(e);     //output :     java.lang.NullPointerException
                e.printStackTrace;        //output :    java.io.IOException at package.Test.main(Test.java:74)
                                       
            }catch (Exception e){        //Catches all sorts of Exception should be placed LAST
                                        //If passed 1st any catch block belowing will be skipped
            }finally{
            }

           
    4. Multiple catch Using OR (|)
            try {
            do something ;
            }catch (FileNotFoundException | IOException e){ //Catch executes when either of the 2 exception occur
           
            }

           
    5. What you can do inside catch block ?
        -    e.printStackTrace()
        -    e.getmessage();
        -     log.error("Ops!", e); //Using logging framework like logback or log4j
        -     "USER CAN DO ANY OPERATIONS"
       
    6. What is Throwable t ?
        -    In normal cases we should always catch sub-classes of Exception.
       
        Example :
            try {
            do something ;
            catch(throwable t){ //"throwable" is super class of exception
               
            }

       
       

    Excel :Create Drop Down in Excel Sheet(Test Data) with colored font

    Create Drop Down in Test Data with colored font


    To add this drop-down list to a sheet, do the following:
    1. Create the list in cells A1:A4. ...
    2. Select cell E3. ...
    3. Choose Validation from the Data menu.
    4. Choose List from the Allow option's drop-down list. ...
    5. Click the Source control and drag to highlight the cells A1:A4. ...
    6. Make sure the In-Cell Dropdown option is checked. ...
    7. Click OK.
    Color coding a drop-down list in Excel's 
        1) Create your drop down list in any cell using Data Validation with fields. e.g, Low, Medium,High
        2) Highlight the drop down cell.
        3) Select Conditional Formatting
        4) Select Highlight cell rules, more rules
        5) Select Format only cells that contain
        6) Change the value in the format only cells with: to Specific Text
        7) Enter the text field . e.g. Low
        Select Format tab.
        9) Select the Fill tab and select your colour e.g. Green.
        10) Click Ok