Monday, 24 June 2013

Handling switch over from one window to another using Selenium Webdriver

This script helps you to switch over from a Parent window to a Child window and back cntrl to your Parent Window

String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
for(String windowHandle  : handles)
{
if(!windowHandle.equals(parentWindow))
   {
     driver.switchTo().window(windowHandle);
      <!--Perform your operation here for new window-->
driver.close(); //closing child window
    driver.switchTo().window(parentWindow); //cntrl to parent window
    }
}

Tuesday, 4 June 2013

Cross-browser testing on Cloud using Python + RC + Sauce Labs

Generally, cross browser tests are done manually on Browserstack;  We can do the same using Selenium with Python bindings.

Selenium RC: JSON configuration
Sauce-specific settings are given inside Selenium's "browser" parameter. This is generally a string in the form "*browser" (e.g. "*iexplore", "*firefox"), but will now need to be a full JSON object like this:

{
"username": "your username here",
 "access-key": "your access key here",
 "os": "Linux",
 "browser": "firefox",
 "browser-version": "3"
}

Python Code:

#! /usr/bin/env python
#-.- coding=utf8 -.-

from selenium import selenium
import unittest, time, re

class login(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("saucelabs.com",
                                 4444,
                                 """{
                                     "username": "your-sauce-username",
                                     "access-key": "your-access-key",
                                     "os": "Linux",
                                     "browser": "firefox",
                                     "browser-version": "20"
                                 }""",
                                 "http://salesforce.com/")
        self.selenium.start()
        self.selenium.set_timeout(90000)
    
    def test_empty_info(self):
        sel = self.selenium
        sel.open("/in/")
        sel.click("id=button-login")
        sel.wait_for_page_to_load("30000")
        sel.type("id=username", "james")
        sel.type("id=password", "connor")
        sel.click("id=Login")
        sel.wait_for_page_to_load("30000")
        try: self.assertEqual("Your login attempt has failed. The username or password may be incorrect, or your location or login time may be restricted. Please contact the administrator at your company for help.", sel.get_text("css=div.loginError"))
        except AssertionError, e: self.verificationErrors.append(str(e))

     
    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

Note:- Reports are generated as log and video



Thursday, 16 May 2013

Print Eclipse IDE console output on a text file after Test execution


Following setting will print your eclipse console output on a separate Text file.

1| Create a text file (.txt) in your project folder
2| In Eclipse, right click Project > Run configurations
3| Click the Tab, "Common"
4| Select the Check boxes, File & Append
5| Now choose the correct directory and select the empty text file you created before
6| Click ok
7| Run the Test
It looks simple and an eclipse configuration :)

Locate and select Auto suggest on search field for a List item (/li) using WebDriver

The below code is for searching a text automatically from the auto suggest; mainly for a list item.

driver.get("http://www.indiabookstore.net");
driver.findElement(By.id("searchBox")).sendKeys("Alche");
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("/html/body/div[4]/ul/li"));
listItems.get(0).click();
driver.findElement(By.id("searchButton")).click();
    
Note:  We can also repalce the xpath locator,
By.xpath("/html/body/div[4]/ul/li") with By.xpath("//div[4]/ul/li")

It's not a better way to use the above xpath locator; meanwhile these locators can be replaced with one of the following options (use csslocators for better solution).
List <WebElement> listItems = driver.findElements(By.xpath("//div[contains(@class,'acResults')]//li"));    
List <WebElement> listItems = driver.findElements(By.xpath("//div[@class='acResults']//li"));
List <WebElement> listItems = driver.findElements(By.cssSelector(".acResults li"));
List<WebElement> link = driver.findElement(By.id("Element")).findElements(By.tagName("li"));

get(0) is the first option displayed on searching keywords
get(1) is the second option displayed on searching keywords















Anchor Tag :

HTML

<head>
<body id="data-search" class="hassidebar">
<ul id="material-result-list" style="top: 183px; left: 396.5px; width: 270px; display: block;">
<li>
<a>nitrate/0.2</a>
</li>
</ul>

CODE

Here, we need to click on specific anchor tag.

List<WebElement> listItems = driver.findElement(By.id("material-result-list")).findElements(By.tagName("a")); 
listItems.get(2).click();

Thursday, 2 May 2013

Handle iFrames | Selenium

It's easy to work with iFrames.  First, try to find all the iFrames available in web page;  Next, switch into the iframe and then come out of the iframe.


Snippet

try{
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[id='Value']")));
      new WebDriverWait(driver, 5)
      .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("Value")));
System.out.println("Element found");
}catch (TimeoutException e) {
      System.out.println("Element not Found");     
  }
}

How to Terminate iFrame?
To return back from the current iframe to main content, make use of the following script,

driver.switchTo().defaultContent(); 

Handle iFrames without id | name
 
driver.switchTo().frame(0);




Check iFrames availability

Google Chrome
Use Chrome Developer debugging Tool to find all the available iFrames in the web page.




1| Open chrome web Browser
2| Press F12 key
3| Press Esc key
4| In console, you will see a filter icon followed by the dropdown <top frame>
5| Click on the dropdown to see the iFrames availability.

mozilla Firefox
Use the Firefox addon, web-developer to find all the available iframes in a web page. Selecting 'Outline Frames' lets you highlight the web page UI with iframes.



Wednesday, 20 March 2013

How to store & assert HTML-meta-tag?


<META> tag is a special HTML tag that provides information about a Web page. Metadata will not be displayed on the page, but will be machine parsable.

Unlike normal HTML tags, meta tags do not affect how the page is displayed. Instead, they provide information such as,
  • who created the page(author), 
  • how often it is updated, 
  • what the page is about(page description), and 
  • which keywords represent the page's content. 

Many search engines use this information when building their indices. This is how it looks:

<head>
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Ståle Refsnes">
<meta charset="UTF-8">
</head>

Note: <meta> tag always goes inside the <head> element.

Store & Assert <meta> tag 'Description' content:

1. Use the command, "storeAttribute" for storing contents present inside the <meta> tag.
2. Insert the xpath //meta[@name='description']@content in Target field.
3. Now store the value and print it.

storeAttribute  |  //meta[@name='description']@content  |  variable
echo  | ${variable}


Java code for store and assert <meta> tag description contents:

String variable= driver.findElement(By.xpath("//meta[@name='description']")).getAttribute("content");
System.out.println(variable);
assertEquals("your text", variable);

Monday, 18 March 2013

Headless Browser Testing using PhantomJS - GhostDriver | WebDriver


PhantomJS is a Headless Webkit with JavaScript API. It has fast & native support for various Web Standards: DOM handling, CSS selector, JSON, canvas and SVG.  GhostDriver is a Webdriver wire protocol in simple JS for PhantomJS.  PhantomJS is used for Headless Testing of Web Applications that comes with in-built GhostDriver.

Involves,
1| General command-line based testing.
2| As a part of a Continuous Integration System.

PhantomJS is not a Test framework, it is used only to LAUNCH the tests via a suitable Test Runner.

Framework used: WebDriver
Test Runner: GhostDriver

CI systems: Make sure PhantomJS is installed properly on the slave/build agent and it is ready to go. Headless Browser is a Web Browser without a GUI (Graphical User Interface). It access Web Pages but doesn't show them to any human being. Headless Browser should be able to parse JavaScript.



Configure PhantomJS

1. Download phantomjs.exe
2. Extract the phantomjs-1.8.x-windows.zip folder and locate phantomjs.exe file to C:/ folder
3. Add the following imports to your code:

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

4. Replace the object, "driver" specifying "FirefoxDriver" with "PhantomJSDriver".

Replace the code,
WebDriver driver = new FirefoxDriver

with
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true); // not really needed: JS enabled by default
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(caps);

5. Run Test.

Note|
PhantomJSDriver-1.0.x.jar can also be downloaded and configured in Eclipse manually.



PhantomJS | Screen Capture

DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true); // not really needed: JS enabled by default
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C://phantomjs.exe");
caps.setCapability("takesScreenshot", true);
driver = new PhantomJSDriver(caps);  
baseUrl = "http://www.xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test01() throws Exception {
driver.get(baseUrl + "/");   
long iStart = System.currentTimeMillis(); // start timing
<your script>
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\sample.jpeg"),true);    
System.out.println("Single Page Time:" + (System.currentTimeMillis() - iStart)); // end timing    
}

Friday, 8 March 2013

Load Default/Custom Chrome Profile to run tests using Selenium WebDriver

1. Download Chromedriver 2.4
2. Extract the zipped folder chromedriver_win32.zip and locate .exe file to C:/ folder

System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);

If you face such error:
"org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally"

Then try to create a new Chrome profile and execute tests.

1| Copy the folder, 'User Data' and paste it on the same folder with different name. e.g., New User
2| Open the folder, 'New User'.
3| Rename the folder, 'Default';  so that after your test run, a new folder named, 'Default' will be created.
4| Now, replace the directory on your code with C:/Users/user_name/AppData/Local/Google/Chrome/New User
5| If you like to test the profile, then bookmark some of the sites & observe them on next run.

Note:-
IE doesn't need profile setup to run tests because they run on Server user while Firefox and Chrome works with binary.

Thursday, 21 February 2013

Handle Alert Popup | Modal dialog

PopUps

Web Applications generate 3 different types of PopUps;  namely,

     1| JavaScript PopUps
     2| Browser PopUps
     3| Native OS PopUps [e.g., Windows Popup like Upload/Download]

JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle JavaScript pop-ups

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

accept(), dismiss(), getText(), and sendKeys() are some of the most important Alert functions.



Handling JS PopUp


#Print Alert Text and Close


    import org.openqa.selenium.Alert;

    Alert alert = driver.switchTo().alert();
    System.out.println(closeAlertAndGetItsText());

    private String closeAlertAndGetItsText() {
      try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println(alertText); //Print Alert popup
        if (acceptNextAlert) {
        alert.accept(); //Accepts Alert popup [OK]
        } else {
        alert.dismiss(); //Cancel Alert popup
        }
        return alertText;
        } finally {
        acceptNextAlert = true;
        }
        }


#Assert Alert Text


    Alert alert = driver.switchTo().alert();
    assertEquals("Expected Value", closeAlertAndGetItsText());


isAlertPresent()


    driver.findElement(By.id(Value)).click();
    isAlertPresent();

    private void isAlertPresent() {
        try {
        Alert alert = driver.switchTo().alert();
         System.out.println(alert.getText());
         alert.accept();       
        } catch (NoAlertPresentException e) {
         System.out.println("Alert not available");
                return;
        }
      }

Tuesday, 19 February 2013

How to set proxies with Username and Password in FirefoxDriver


Setting up Custom Firefox Profile to run Selenium Tests on Desktop Firefox

Even though Selenium – WebDriver – FirefoxDriver – Proxy with Basic/Kerberos Authentication didn’t work, you can achieve this with an alternate step that overrides Firefox browser Proxy Authentication.

The alternate step is nothing but allowing WebDriver to run tests on default/custom Firefox profile rather than running from FirefoxDriver.

Note:
In Selenium 2.0 (WebDriver) every popular browsers has its own selenium drivers to run tests.

Let us go with the concept now…


Create Firefox Profile Manager

Important: Before you can start the Profile Manager, Firefox must be completely closed.

1. At the top of the Firefox window, click on the Firefox button and then select Exit
2. Press Win + R (click the Windows Start button and select Run... on Windows XP).
3. In the Run dialog box, type in:
    firefox.exe -p
4. Click OK.



5. Now, create the firefox profile "myProjectProfile".

If the Profile Manager window does not open, Firefox may have been running in the background, even though it was not visible. Close all instances of Firefox or restart the computer and then try again.

Add this New Firefox Profile on your code

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("myProjectProfile");
WebDriver driver = new FirefoxDriver(myprofile);

Firefox configuration settings

This works fine without prompting any authentication when you do the following settings..

1) Type "about:config" on your FF url
2) Now type "Proxy" in the search field
3) Make sure "signon.autologin.proxy" is set "true" (By default it is "false")