My Blog List

Thursday, November 24, 2011

Top Security Testing Resources / Tools

A big community called "OWASP - Open Web Application Security Project" releases information about  software vulnerabilities for every year. Also you can learn lot of concepts here.
Here I have done listing of some security testing tools known,

Commercial Tools:
IBM Rational AppScan
HP QA Inspect
HP WebInspect
HP Fortify
Cenzic Hailstorm

OpenSource Tools:
WebScarab by OWASP community
SkipFish - by Google

Sunday, November 20, 2011

Some good Resources / Blogs / Sites for Selenium Users

Here I have listed out some good blogs and sites by extensive selenium automation users. Hope these will help you a lot. - by NirajKumar  - by Naga/Mathu - by Farheen Khan - Amit Vibhuti

Sauce Labs and BrowserMob are companies doing cloud and extensive selenium automation services, products, etc

Cedric Beust - creator of the TestNG Java testing framework. - by Samit Badle, Created many Selenium IDE Plug-Ins

Available Colud Testing:
1. SauceLabs
2. Soasta
3. BrowserMob
4. etc.

Selenium Testing Products:
1. Twist by ThoughtWorks
2. TestMaker by PushToTest
3. Element34 company providing selenium testing services, etc.

Monday, November 14, 2011

Selenium - waitForCondition with JavaScript Expressions

Selenium provides select method to select an item/option from drop-down lists and comboboxes. But this will work for simple listboxes only. For complex comboboxes like textbox with image, clicking the image will open drop-down list will not support normal methods. Here I am listing out different ways to handle select boxes. Thanks to bloggers as I read these from one and more blogs.

Consider the following example where there are two drop-downs, one for the states and the other for counties.
The county drop-down is populated based on the state selection.
You can see in the site above, when the state is selected, a spinner shows up for a few seconds before the county drop-down is populated. 
Here we are using waitForCondition as it allows to mention explicitly TIMEOUT whereas selenium provided waitFor allows only default TIMEOUT value.

1. Dependent drop-down Lists using waitForCondition
Using waitForCondition and some JavaScript, we wait until display style attribute changes to ‘none’ in the snippet below.
  2. selenium.selectFrame("mainFrame");
  4. selenium.waitForCondition("var value = selenium.browserbot.findElementOrNull('loading_county_drop_down'); == 'none'","10000");
  5."county""label=Amador County");

2. Using waitForCondition for multiple Conditions
  1. selenium.waitForCondition("var value = selenium.browserbot.findElementOrNull('loading_county_drop_down'); == 'none' || selenium.browserbot.getUserWindow().document.form.county.options[0].text == 'Select a county of California';""10000");

3. Using waitForNotVisible and/or waitForSelectOptions
  1. selenium.waitForNotVisible("loading_county_drop_down");
  2. selenium.waitForSelectOptions("county","regexpi:Amador County");

4. Progress Messages:
You may have seen many AJAX intensive sites displaying a ‘Loading..’ or ‘Saving..’ or ‘Processing…’ message when a button or a link is clicked. In such cases you may find this to be helpful to wait for the status text to change or disappear.
Assuming that a ‘Saving’ message is displayed within a div tag when a fictional ‘Save’ button is clicked in the snippet below:
  1. selenium.waitForCondition("var value = selenium.getText(\"//div[@class='save-text']\");value != \"Saving\"""20000"); 
In general, .Net sites that use the web form controls, panel controls etc, trigger an asynchronous postback everytime a form control is filled or a .Net tab or panel control is clicked etc. In such cases, I’ve found the following to be very helpful in waiting for the postback to complete.
  1. selenium.waitForCondition("selenium.browserbot.getUserWindow().Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack() == false;","10000"); 
Now for the killer part, for sites that use jQuery, if all you need is to confirm there aren’t any active asynchronous requests, then the following does the trick:
  1. selenium.waitForCondition("selenium.browserbot.getUserWindow().$.active == 0""10000");
As you can see, there are several possible variations to a single command. The possibilities are endless with Selenium.

Selenium - Drag and Drop Operation

The inbuilt dragAndDrop function provided by selenium RC classes will do the expected operation well easily. Some times its difficult to do drag and drop operations like drop on particular element, etc. Here is the approach.

1. Drag an element to drop on to another element:
  1. driver.get("myURL");
  2. var from = driver.findElement(By.xpath("fromElement"));
  3. var to = driver.findElement(By.xpath("toElement"));
  4. new Actions(driver).dragAndDrop(from, to).build().perform();

2. Drag an element to an offset:
  1. driver.get("myURL");
  2. var dragElement = browser.findElement("ElementToDrag"));
  3. new Actions(driver).dragAndDropBy(dragElement , 20010).build().perform();

Selenium - Handle JavaScript Alert and Confirmation boxes

Confirmation boxes  and Alerts are handled in same way in selenium.

  1. var alert = driver.switchTo().alert();
  2. alert.dismiss();  //Click Cancel or Close window operation
  3. alert.accept();   //Click ok

Handle Confirmation boxes via JavaScript,
driver.executeScript("window.confirm = function(msg){return true;};");

Selenium - Handle Iframes/Frames easily

Hi all,
Here I am going to list out ways to handle iFrames parts in selenium automation as I read from some sites.

  1. //Gmail Body is an iframe. Here we are writing content to body of new mail in selenium
  2. var bodytext="Sample Body Text for Testing";  
  3. var iframe_locator = "css=table:contains('Subject:') +*  iframe\";
  4. var iframe_body = selenium.browserbot.findElement(iframe_locator).contentWindow.document.body;
  5. if (browserVersion.isChrome) {    
  6.   iframe_body.textContent=bodytext;
  7. }  else if(browserVersion.isIE) {
  8.   iframe_body.innerText=bodytext;
  9. }


  1. //Switch to the frame - use index/name
  2. driver.switchTo().frame("frameName"); 
  3. //Also you can use like 

    // Do your operations in frame 
  4. //Switch back to the parent window
  5. driver.switchTo().defaultContent();

Sunday, November 13, 2011

Selenium Rare Tips - Part II

1. Get Browser Name, Version and Environment Details
Java Script Expressions which you can use by Selenium.getEval to get the values.

  1. navigator.appCodeName   //For Browser Name
  2. navigator.appVersion    //For Browser Version
  3. navigator.userAgent     //For both details
  4. navigator.appName       //For Browser Name
  5. navigator.cookieEnabled //Cookie enabled or not
  6. navigator.platform      //OS

2. Get Current URL

3. Scroll Bar Position

  1. Actual Width/Height of element:(Excluding ScrollBar)
  2. selenium.browserbot.getCurrentWindow().document.getElementByid('css#id').clientWidth
  3. selenium.browserbot.getCurrentWindow().document.getElementByid('css#id').clientHeight
  4. Max Scroll Position:
  5. scrollWidth - clientWidth    //Max Horizontal Scroll Position
  6. scrollHeight - clientHeight  //Max Vertical Scroll Position
  7. Current Scroll Position:
  8. scrollLeft
  9. scrollTop

If you are using Selenium 1.0, use this.browserbot
If you are using Selenium 2.0, use selenium.browserbot

4. JavaScript Expression execution in Selenium 2.0

  1. JavascriptExecutor js = (JavascriptExecutor)driver;
  2. String title = (String) js.executeScript("return document.title");
  3. System.out.println(title);
  4. String script = "var ele = document.getElementsByTagName(\"a\");" +
  5.                 "return ele[0].getAttribute(\"title\");";
  6. String titleName = (String) js.executeScript(script);

Thursday, November 10, 2011

Add Custom functions to Selenium

We can add custom functions to selenium or extend your selenium jar functions as you want. We can do this in 2 ways.

1. Extending selenium-browserbot.js and selenium-api.js
     a. Extract your selenium-server-standalone-xxx.jar to temp folder.
     b. Find the files selenium-browserbot.js and selenium-api.js inside core\scripts\ folder.
     c. Add your custom function to class BrowserBot like below in selenium-browserbot.js.

  1.  BrowserBot.prototype.yourFunctionName = function() {
  2.                    //code here
  3.         }

     d. Now add your function to class selenium to expose Selenium API like

  1. selenium.prototype.yourFunctionName = function() {
  2.               return this.browserbot.youFunctionName();
  3.          }

     e. Thats all. Re-bundle your JAR file with updated files. Your Selenium-Server JAR file  is ready with your custom functions.

Here is the example code:

  1. BrowserBot.prototype.getAllRadios = function() {
  2.        var elements = this.getDocument().getElementsByTagName('input');
  3.         var result = [];
  4.         for (var i = 0; i < elements.length; i++) {
  5.            if (elements[i].type == 'radio') {
  6.                result.push(elements[i].id);
  7.            }
  8.         }
  9.          return result;
  10.  };

To add in selenium-api.js,
  1. Selenium.prototype.getAllRadios = function() {
  2.       return this.browserbot.getAllButtons();
  3. };
So this is a appraoch to extend your Selenium functions. But this approach have risk of altering/damaging existing selenium functions in the JAR package. Thats why they provided a option called User-Extensions.

2. User-Extension.js
a. Just add your custom functions in user-extensions.js by adding function to class selenium.
b. Important point is, here you have use getDocument() for browserbot to do your operations.
c. Finally just start your selenium server JAR with your user-extenstions.js like
java -jar /selenium-server-1.0.1/selenium-server.jar -userExtensions /user-extensions.js
d. Thats all. Your functions are available now in JVM.
e. To use this, create instance for httpCommandProcessor and use doCommand(yourFunctionName) OR simply selenium.youFunctionName.

Here is the example code:

  1. Selenium.prototype.getAllRadios = function() {
  2.        var elements = this.browserbot.getDocument().getElementsByTagName('input');
  3.        var result = [ ];
  4.        for (var i = 0; i < elements.length; i++) {
  5.            if (elements[i].type == 'radio') {
  6.                result.push(elements[i].id);
  7.            }
  8.       }
  9.        return result;
  10. };

Hope this helps you to create your own functions to extend your selenium-server.jar.

Wednesday, November 9, 2011

Selenium Rare Tips - Part I

Hi all,
Here I am going to list out some rare and useful tips for selenium users.

1. Start/Shutdown SeleniumServer in proper way
  1. public static void startSeleniumServer() throws Exception {    
  2.     try {
  3.         ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
  4.         serverSocket.close();
  6.                 //Server not up, start it
  7.                 try {
  8.                          RemoteControlConfiguration rcc = new RemoteControlConfiguration();
  9.                          rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
  10.                          server = new SeleniumServer(false, rcc);    
  11.                 } catch (Exception e) {
  12.                         System.err.println("Could not create Selenium Server because of: " + e.getMessage());
  13.                         e.printStackTrace();
  14.                 }
  16.                 try {
  17.                         server.start();
  18.                         System.out.println("Server started");
  19.                 } catch (Exception e) {
  20.                         System.err.println("Could not start Selenium Server because of: " + e.getMessage());
  21.                         e.printStackTrace();
  22.                 }
  24.         } catch (BindException e) {
  25.                 System.out.println("Selenium server already up, will reuse...");
  26.         }
  27. }

  1. public void tearDown() throws Exception {
  2.     selenium.stop();
  3.     if(seleniumServer != null) {
  4.         try {
  5.             selenium.shutDownSeleniumServer();
  6.             seleniumServer .stop();
  7.             seleniumServer = null;
  8.         }  catch(Exception e) {
  9.             e.printStackTrace();
  10.         }
  11.     }
  12. }

OR you want to shoudown via Browser, use below command

2. To Scroll by postion
--- Here 0 and 200 are x and y postions to scroll

3. Get No of CheckBoxes Checked/Unchecked
  1. selenium.getXpathCount("//input[@type='checkbox' and @checked]");
  2. selenium.getXpathCount("//input[@type='checkbox' and not(@checked)]");
    Also You can use like

4. Drop-down lists handling
To get selected value:
  1. selenium.isElementPresent("//select[@name='listbox']/option[contains(text(),'item2')]")
  2. selenium.getSelectedValue("name=listbox");

To get list items:
String[] items = selenium.getSelectOptions("name=listbox");

To set or select a item on dropdown:"listbox""label=item1");         //For Simple Select List

There is a select list, which contains a text box and down arrow image button. Clicking on button image, opens a drop down which contains element with dynamic id's.
Dynamic elements are : drop down elements (div's) , and image button.
This can be done by"//input[@id='listbox']/following-sibling::img");
This clicks on image. Now we need to select the dropdown list element, which also has dynamic id.
So, I have used text function as,"//div[text()='item1']");            //which clicks on "item1" in the drop-down list.
Also have a look at this link Select an option from an ExtJS ComboBox

5. HTTP to HTTPS problems

6. Locate Elements by position
If you have 2 buttons on a page. Both have same ID, type, and available attributes are same. How you will identify which element to click?. Here is the answer.

  1. //input[@id='button' and position()=1] OR //input[@id='button']  //1st button
  2. //input[@id='button' and position()=2]    //2nd button

7. XPath Type : Functions
Always we have chances to meet locator problems while elements with same attributes, ids, names, etc. These kind of scenarios can be solved by using below techniques. Normally we can use 4 ways to identify the elements.
1. String
2. Boolean
3. Number
4. Node-Set
Here they are,
  1. Node-Set: last(), position(), count(), id(), local-name(), namespace-uri(), name()
  2. String: string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
  3. Boolean: boolean(), not(), true(), false(), lang()
  4. Number: number(), sum(), floor(), ceiling(), round()
Here are some examples.