Friday, July 31, 2015

Support

- https://episteme.cognizant.com/uploads/2014/11/C-R-A-F-T-Selenium-handbook.pdf


- Java documentation:
http://docs.oracle.com/javase/7/docs/api/

- Selenium documentation for Java
http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html


Sunday, July 12, 2015

Handson

- Identify from the dealer names in the Hyundai website

- Implement Craft on Amazon application.

- Connect Excel from Eclipse and read data

Selenium RC to WebDriver migration

- Selenium WebDriver is faster than RC

- Selenium RC has no better support, new elements does not have support.

- Steps to be followed to migrate existing Selenium RC project:

Create Selenium instance from webDriver

WebDriver driver = new FirefoxDriver();

Selenium selenium = new WebDriverBackedSelenium(driver, http://www.goggle.com);

Now use WebDriverBackedSelenium instance in test scripts and see that all test cases are passing.

-

Frames

  • Frame:
  • Here we are trying to click the link, that is inside the frame.

    driver.switchTo().frame("<name of the frame>");
    driver.findElement(By.linkText(<"name of the text>")).click();

    driver.findElementt(By.tagName("frame")).size() --- gives number of frames available

    -

     

    Handling External files


    POM --- Page Object Model

    1/12/2016

    Collecting WebElements and Methods respective each page.

    Writing separate class for business Components(class A) and web elements (class B)

    Grid

    Refer to blog for more details: This website has complete command and screenshots associated with GRID.
    https://www.learn-automation.com



    - This is the last type of Selenium types. It supports the scripts written in older versions of Selenium.

    - Grid --- distributing the test cases into multiple systems. So make sure systesms are marked sub or hub accordingly. Here test cases can be executed acrosss multiple test cases in multiple browsers in parellel

    - Hub system - distributes the tc's across sub and collects the results.

    - Sub (node) system - executes the tc's assigned by Hub system

    - This helps in compatability testing

    - Using DesiredCapability object we can assign the browser settings we need to use.

    Node matches if all the requested capabilties are met, so to request specific capabilities on the grid specify them before passing the it into the WebDriver object as mentioned below:

    DesiredCapabilities capabilityobject = DesiredCapabilities.firefox();
    capabilityobject.setBrowserName("firefox");
    capabilityobject.setPlatform("LINUX");
    capabilityobject.version("3.6");

    WebDriver driver = new RemoteWebDriver(new URL(http://HubIP:4444/wd/hub), capability);



    Difference between Selenium Grid and QTP remote connection for CI?

    Based on the training- Jan 2016
     - QTP remote connection using Jenkins will need QTP installed on all the remote machines. Once remote machines are all set up, Jenkins will connect those machines and execute test cases instead of you doing it manually(clicking the run button).

    - Selenium Grid, looks like advanced concept compared with QTP remote connection. Here we need systems to be distributed as node and hub, and node does not need Eclipse installed on them just hub will need. Hub will connect respect node, make use of the nodes to execute the scripts in multiple machines (node) and browsers.


    Real code executed on my personal machine by registering hub and node on same machine:
    package seleniumGridconceptsProject;

    import java.net.MalformedURLException;
    import java.net.URL;

    import org.openqa.selenium.Platform;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;

    public class ExecutingGrid {

    public static void main(String args[]) throws MalformedURLException { //Not sure about this exception, added due to URL class

    DesiredCapabilities dc = DesiredCapabilities.chrome(); //path of chrome driver is given while registering node and hub

    URL url = new URL("http://192.168.0.12:4444/wd/hub");  // it can be hub url or node url. This will tell trigger class to trigger on which node. If you give hub url then hub will take care of which node to pick on its own.

    WebDriver driver = new RemoteWebDriver(url,dc);

    driver.get("http://learn-automation.com/");

    System.out.println("Printing through Grid");

    }
    }

    /* Prerequisites: Selnium webdriver jar and Selenium Standalone jar
              *Register hub:Open cmd
           * Navigate to selenum jar file folder
    * enter below command:
    * java -Dwebdriver.chrome.driver= "path of driver file" -jar seleniumjarname -hub
    *
    * Once registered as hub, 
              * Register Node:
              *Enter below command in another session of command prompt t
    * Navigate to selenium jar file folder
    * enter below command:
    * java -jar selenium jar name -role node -hub "hub url"
    *
    *
    */












    Implicit and Explicit waits

    - Implicit wait is common --- its applicable for driver object

    Once used we need not use repeatedly.
    - Explicit wait -- we cannot mention the time unit

    - Implicit wait checks, if element is present or not.

    Explicit also checks the status of the element(we can give the different conditions of the presence of the element not just preset...like is element enabled,

    - Compared with Thread.sleep(<millisecs>") .. we have few differences

    - syntax:

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); --- it will wait for the web element as it checks the element for every seconds, if it available then move on(not waiting till the 10 seconds).

     -

     

    AutoIt


    JUnit


    Junit Notes:

    - Junit and TestNG are testing framework.
    - Junit is not meant for Selenium but for selenium we could use it
    - Junit is Jar file, inorder to use Junit we need to just download the jar file and give the build path in eclipse else right click import jar file when you get the error. Like Add Junit 4 library to the build path and execute by right clicking and then click Run As->Junit test
    - Annotations help you control the execution of script in Junit
    - When you are using Junit framework, one need not mention main method???
    - Annotations list:
    @Test   --- Test Case. If you mention @Test in the front of a class then it means that class would be execute as a test case(test case would be created in framework).
    @Before
    @After
    @Beforeclass
    @Afterclass
    @Ignore
    @RunWith(Suite.class)  --- helps to Run the classes in batch
    @SuiteClasses( ------- batch in classes
    {class1},
    {class2})
    @Rule


    - In @Test, if you mention word 'Test' in method name then @Test annotations script would be executed in an order
    - @After and @Before - are tagged to @Test. @After and @Before gets executed for everywhere @Test. To avoid this we have
    - Assume.assumeTrue(<True>) ---
    - Assertions
    Assert.assertEquals(Expected, Actual)
    - Drawback on Assertions(above statement) if Assertions fails then rest of the script will not be executed so we use try and catch.
    Like:
    try{
    Assert.assertEquals(var1,var2)
    }catch(Throwable t){
    system.out.println(




    - JUnit - Java Unit ---- as we use Java language. Different languages have different units.

    - Csharp -- we use Test

    - JUnit ---- has annotations, thats why we use units.

    Source: http://www.tutorialspoint.com/junit/junit_overview.htm



    Features

    • JUnit is an open source framework which is used for writing & running tests.
    • Provides Annotation to identify the test methods.
    • Provides Assertions for testing expected results.
    • Provides Test runners for running tests.
    • JUnit tests allow you to write code faster which increasing quality
    • JUnit is elegantly simple. It is less complex & takes less time.
    • JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results.
    • JUnit tests can be organized into test suites containing test cases and even other test suites.
    • Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.


    It will just follow annoations instaed of going throug main method, ordering of executing the code could be changed using annoations(JUnit).







    Annotation most freq used for testing are:
    @Before  -- method that is marked @Before will be executed before executing every test in the class.
    @After
    @Test
    @BeforeClass
    @AfterClass

    - To create JUnit test case:
    Go Eclipse IDE-> right click on your package -> JUnit test case

    Provide class name(JUnitTest), you will have checkboxes for selecting annotations-- select setup() and teardown()

    Once you are done with the test case, here is how you better mention before and after as below:

    public class JUnitTest {
    @Before
    public void setUp() {
    System.out.Println("first");
       }

    @After
    public void tearDown() {
    System.out.Println("third");
      }

    @Test
    public void test1() {

    System.out.Println("second1");
    }
    }
    @Test
    public void test2() {

    System.out.Println("second2");
      }
    }

    output:
    first
    second1
    third
    first
    second2
    third

    - See JUnit will help you to create see test case in the results.

    Assertion - is to indicate whether the particular statement returning true or false.
    - assertEquals("<actualvalue>", "<expected>"); --- compares actuals with expected, and produce true or false in the results.  ---- you need not seperately write code to validate

    assertEquals("Google",driver.getTitle());

    - assertTrue()
    sub methods used with assertTrue() are
    isEnabled()
    isDisabled()
    isSelected()

    -   What are the packages that needs to be included???






    Alert box, pop ups, secuirty pop ups etc

    SwitchTo()...


    Alert:
    Alert alert = driver.switchTo().alert();

    alert.accept();

    - To get the text in the alert box, use something like alert.getText()

    - If you get multiple alert boxes(that means handled you get ono more). -----Alert????

    If I need to select ok on one alert box and then cancel on next alert box.

    getText() -- help us to find the text of alert box, so write condition with text method, based on content mention alert object accept() or cancel() methods.

    - You will sometime not get alert but code written, so make use of exception  handler. Saying that if there is not alert handle it saying that code should be continued.

    -

    Get Control on the window

    • Switching control between two windows
    • We need to make use of window ID(dynamic in nature, has around 30 alphanumerica character)
    • driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
    • File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
              FileUtils.copyFile(src, new File("<path>"));

    Note: take the control of the window, using window id and take screenshot to make sure on which window we had control.

    • From Episteme:

    1. Basic idea to handle window is, once new window open get the number of window & switch to child window.
    2. Do some operation & close the session using driver.close.(In your case window is closing automatically but may not current session ended)
    3. Once close the window, check once again how many windows open & switch to current window using name or index
    Step 1: Get the parent window handle using below statement.
    String parentwindow = driver.getWindowHandle();
    Step 2: Clickon link to open modal window.
    Step 3: Iterate through all opened windows with help of for each loop.
    for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle);
    popup=driver.switchTo().window(winHandle);
    if(popup.getTitle().equals(“title of the window to which you have to switch”))
    {
    ….
    break;
    }
    }
    Sleeper.sleepTightInSeconds(2);
    driver.close();
    Sleeper.sleepTightInSeconds(5);
    driver.switchTo().window(parentwindow);
    Step 4: Trying to switch back to parent window using below statement.
    driver.switchTo().window(ParentWin);

    Saturday, July 11, 2015

    Action class, mouse over actions

    Actions <object name>= new Actions("<driver object>");

    <object name>.moveToElement(<driver object>.findElement(By.linkText("<value>")).build().perform();  




     ----- Action part will be working within the browser.

     Here for mouse over we need to create Actions object by giving drivers object. And using Actions object we can do moveToElement method on a web element.


    - to perform few more operations after moving the mouse

    After you make moveToElement is made, if you have list of options in it, so better do again moveToElement and then find the element and click it.

    - Source: http://stackoverflow.com/questions/17293914/how-to-perform-mouseover-function-in-selenium-webdriver-using-java

    Code:
    1. Hover over a menu item.
    2. Find the hidden element that is ONLY available after the hover.
    3. Click the sub-menu item.
    If you insert a 'perform' command after the moveToElement, it moves to the element, and the sub-menu item shows for a brief period, but that is not a hover. The hidden element immediately disappears before it can be found resulting in a ElementNotFoundException. I tried two things:
    Actions builder = new Actions(driver);
    builder.moveToElement(hoverElement).perform();
    builder.moveToElement(clickElement).click().perform();
    This did not work for me. The following worked for me:
    Actions builder = new Actions(driver);
    builder.moveToElement(hoverElement).perform();
    By locator = By.id("clickElementID");
    driver.click(locator);

    Using the Actions to hover and the standard WebDriver click, I could hover and then click.



    Scenario:

    To click the sign in button in Amazon home page:
    Solution:


    WebElement obj2 = obj1.findElement(By.xpath("//*[@id='nav-link-yourAccount']/span[2]")); //My account element
     

    Actions act1  = new Actions(obj1);


    act1.moveToElement(obj2).perform();

    act1.moveToElement(obj2).moveToElement(obj2.findElement(By.xpath("//*[@id='nav-flyout-ya-signin']/a/span"))).click().build().perform();

    support: http://stackoverflow.com/questions/17293914/how-to-perform-mouseover-function-in-selenium-webdriver-using-java

    Notes:
    moveToElment() - Moves the mouse to an offset from the top-left corner of the element.
    perform() - A convenience method for performing the actions without calling build() first.
    build() - Generates a composite action containinig all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).


    Profile --------SetProperty and including the settings

    - System.setProperty("webdriver.firefox.profile", "default");  --- this code is used to include the profile of the user, every browser will have profile created for a user with the name default.

    See here default is the name of the profile, to create name for the profile:
     Go to run->enter 'profile -f': it will direct to you a page where you could create profile.





     

    Friday, July 10, 2015

    Locators or Idenfying web elements

    Webex training notes:
    7/10/15

    • We have 8 locators, using which selenium webdriver identifies the web element.
    • Using any one of the locators one shouldbe able to identify/locating  element in a web page.
    • <driverobject>.findElement(By.name("email_to[]")).click(); ---here name is one of the locators.
    • Right click on the object and select inspect by firebug. Especially html script will be seen, when you select the code it will highlight the related area in the web page.
    • If the attribute is common across multiple web elements, then we use firepath - xpath.
              For the xpath:
               select the web element, right click -> select inspect by firepath->show absolute xpath.

               driverobj.findElement(By.xpath("<>");

    • If absolute reference is not working we need to go with relative reference(using // in the xpath).
    • The brower that gets loaded using the script, using that we will not be able to inspect the element, because the script uses the default settings of browser. Additional settings that user does will not have impact on the script. To include your settings, we need to create profile using setproperty.
    • Xpath could be created as to make sure it matches related properties that we mention in it, like we do using regular expression.
              Ex: Creating xpath for 3 checkboxes thar are in an order in a web page.

              xpath = //<tag name>[@<attribute name>='<value>'] ....... Since we have picked name attribute here, the inspect element with this xpath will highlight all 3 checkboxes.

    • xpath = //<tag name>[@<attribute name>='<value>'] [1] --- this will locate the first element with the same attribute.
    • We can join two conditions using and
              xpath = //<tag name>[@<attribute name>='<value>'  and @value='1']

    • Use Higlight, adjacent to Xpath section in inspect by Firepath window, when you click Highlight it will show the web element that xpath is refering too. That way you can validate the xpath, whether its pointing out to the proper web element. Dont forget to enter xpath in the field.
    • Regular Expression in xpath:
               xpath = //<tag name>[starts-with(@<attribute name>,'<value>')]

               Following could be used:
               ends-with
               contains
    • Dropdown:
               We need to create object for class Select

               Select <object name> = new Select(<web Element>);

               Ex: Select dd1= new Select(driver.findElement(By.name("subject"));
               dd1.selectIndex(1);
              
              <object name>.selectByIndex("<value>");
              <object name>.selectByValue("<value>")
              <object name>.selectByVisibleText("<value>");

    Lets suppose you wanted to select the last value of drop down, make use of index numders...index starts from 0. But you if you wanted to click the last but one drop down value, you need to know the total number of values in the drop down. To do that activity do the following.

     <object name>.getOptions().size()   ===  gives the total number of values in drop down.


    • xpath:
            //  --- use this if the element is grand child
    xpath = //table[@class='fd']/td[@class='gfhy']
            / ---- use this if the element is direct child
    xpath = //table[@class='fd']//a[@class='asd']

    • xpath:
    Always use @ symbol for the atrributes

    • contains
    • text() --- see i have come across a scenario where I need to select a text that is a hyperlink. Here keep in mind text was not a attribute.
    <table>
    <tc>
    --
    <td class='sdf']
    <a class ='dfs' href='#']Program</a>
    --
    --
    </td>
    --
    --
    </table>//td[@class='sdf']/a[@class='dfs' and text() = 'Program]



    xpath = //table

     - How to send encoded value to Password field...?



    - Source:
    http://blargon7.com/selenium_docs/04_selenese_commands.html

    To find list of commands that we can use in Selenium to locate an object. Its really good.


              

    Drivers for the browsers


    - Go to http://code.google.com/p/selenium/downloads/list?can=1&q=&colspec=Filename+Summary+Uploaded+ReleaseDate+Size+DownloadCount

    Here you can download the drivers wrt to multiple browsers.

    We need to download the respective browser driver.

    See once you download, you tag that downloaded driver file to your script.

    System.setProperty("webdriver.ie.driver", "<driver file path>") --this is for IE browser

    then mention the driver object.

    IE:

    WebDriver driver = new InternetExplorerDriver();

    Note: Disable protected mode should be mentioned in internet options some times. Disable Trusted and restricted sites.

    Note for IE browser:(this helps to skip the settings in IE in some cases if browser is not openining)
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);


    - Firefox:

    WebDriver driver = new FirefoxDriver()

    This will invoke firefox browser and returns an handle in form of WebDriver object which is used to interact with browsers.

    See here the above code is not similar to what we use when we create object for a class, here it is based on super and sub class.
    syntax:
    FirefoxDriver - is a sub class constructor ?? Not solved
    WebDriver - is super class
    driver - is a object

    freqly used methods:
    .get("<url>"); ---- helps u hit the url
    .getTitle();  ---returns the page title
    .close(); -- closes the window that is currently open
    .quit(); --- closes every associated window. If i click link in a web page, the opens another window, so using quit, we can close all those related windows.
    .findElement(By.name("email_to[]")).click();












     

    Selenium(WebDriver) Benefits/Notes

    WEbEx training notes

    Selenium WebDriver Notes(includes advantageous):

    - Selenium is for Web Based applications and QTP is for Web based and Desktop based applications

    - Selenium will handle desktop applications using some third party

    - Selenium supports around 6 languages but QTP supports only Vbscripting.
    Simply download library files from google and continue the existing script(even if it is written in other language).

    - Selenium IDE(add on of firefox), RC, Web Driver and Grid.

    - Selenium uses Javascript drivers to connect Selenium with browsers. Selenium+WebDriver.
    WebDriver is also available for Mobile Testing, we have Andriod and Iphone driver.

    - Steps to download addons: FireFox -> Ctrl+Shift+A (it will go to Extensions page) -> download Firepath and Firebug.

    - Firebug - CSS
      FirePath - Edit, Impact and generate Xpath.

    - For testing use: www.myContactForm.com

    - Go to Seleniumhq.org/download -- to download java driver to work on Selenium.

    - Go to Eclipse Project -> Properties-> Java Build Path- >Libraries ->Add external jar.(the ones that we downloaded from the Seleniumhq.org site).(there should be 39 files that should get added)

    - Eclipse is not a kind of installation file, you just see .exe file in the zip file(Exclipe download file). Everytime you wanted to open the Eclipse you just need to run .exe file.

    - When ever you start programming on identifying objects, right click on the object and select inspect by firepath option. That way you will come to know the xpath of the object. You could use locators.

    - <driver object>.navigate().back(); --- this is navigation command, that is used to navigate back.

    - <driver object>.navigate().forward();

    - <driver object>.manage().window().maximize(); -- this will maximize the browser window
    Mention this under the firefox driver code. But if you are using profile code, dont use it as it will automatically maximizes.

    - To take control on mouse over or keyboard use Action Class object.

    - Verification code in web page, cannot be automated using any of the automation tools.
     
      Using the OCR jar file we should be able to identify such objects.

    -

    -