Monday, November 30, 2009

Avoid XPath when possible
Using XPath as a location strategy for your elements can be dangerous for long term maintenance for your tests as changes to the markup will undoubtedly break your tests. Likewise, certain browsers (cough cough IE) have poor XPath engines and are considerably slower (IE is about 16x slower).
Strangely enough, following accessibility guidelines also makes for better functional UI testing. So instead of XPath locators, consider:
Use "id" whenever feasible.
selenium.Click("close");
Use "alt" tags for images.
selenium.Click("alt=close window");
Use text inside anchor tags when ids or images are not used.
selenium.Click("link=Home");

Avoid timing code
When working with AJAX or Postback events, page load speed can vary per machine or request. Rather than putting timing code in your NUnit code (ie Thread.Sleep), take advantage of one of the selenium built-in WaitFor... selenese commands.
To use, you place javascript code in the condition where the last statement is treated as a return value.// wait 30 seconds until an element is in the DOM
selenium.WaitForCondition("var element = document.getElementById('element'); element;", "3000");
This approach allows your code to be as fast as the browser rather than set to a fixed speed.

Friday, September 25, 2009

Changing Selenium Jar to globally handle Modal Dialog box

  • Unpack Selenium jar. (User JRE jar.exe utility)
  • Open selenium-browserbot.js file.
  • Search for function 'IEBrowserBot.prototype.modifyWindowToRecordPopUpDialogs'"
  • Add following codes at the begning of this function


if(win.showModalDialog)
{
if (typeof(win.top.g_selRetVar) == 'undefined')
win.top.g_selRetVar = null;
win.top._UTL_SetSelRetVar = function (val){
win.top.g_selRetVar = val;
win.top.status = win.top.g_selRetVar + ' is returned from child';
};
win.showModalDialog = function( sURL, vArguments, sFeatures)
{
if ((typeof(win.top.g_selRetVar) != 'undefined') && (win.top.g_selRetVar!=null))
{
var temp = win.top.g_selRetVar;
win.top.g_selRetVar = null;
return temp;
}
try {
win.top.open (sURL, 'modal', sFeatures);
} catch(e){ win.showModalDialog(sURL, vArguments, sFeatures); }
};
}
if(win.close)
{
win.attachEvent('onbeforeunload', function _selhandler()
{
if(win.opener && win.opener._UTL_SetSelRetVar)
win.opener._UTL_SetSelRetVar(win.returnValue);
});
}


  • Pack the jar again. (User JRE jar.exe utility)
If you do not wish to change your jar file you can inject the javascript through your script. This has been mentioned in
Handling Modal windows
Download modified Selenium RC

Tuesday, July 14, 2009

Locator / XPath Generator

Work in Progress. Subscribe yourself to get the release mail.

Basics:
XPath/Locator plays vital role for Selenium automation. XPath for the same control can have various forms. Different people have different way of creating XPath. However best XPath is direct and small. ID is the best option for a locator. Larger the XPath, longer will be the processing time. Same is the case with wild card characters uses. Also 'contains' should be avoided if possible. Its important that XPath should be well constructed. Most of the XPath Generator available generates XPath which is either long or inefficient. This tool will be smart enough to generate best XPath for Selenium automation.

Features to be included:
Direct XPath: Look for Id or the smallest XPath that can identify the element.
Relative XPath: If the element need to be identified relative to another element.

If you have any suggestion or want some feature to be included do share with us.

Friday, June 26, 2009

Check if control is Enabled

public bool IsEnabled(string controlId)
    {
        bool retValue = false;
        try
        {
            string disabled = _selObj.GetEval("selenium.browserbot.getCurrentWindow().getElementById('" + controlId + "').disabled");
            retValue = disabled.ToLower() == "true" ? false : true;
            if (retValue)
                Log.Info(DateTime.Now.ToString() + " : Control " + controlId + " is enabled.");
            else
                Log.Info(DateTime.Now.ToString() + " : Control " + controlId + " is disabled.");
        }
        catch (Exception ex)
        {
            Log.Error(DateTime.Now.ToString() + " : Error occured while determining if control " + controlId + " is enabled");
            throw new Exception("Error occured at SeleniumPage.IsEnabled on '" + controlId + "'", ex);
        }
    return retValue;
}

Avoiding WaitForPageLoad

public bool WaitForBrowserStability(int maxWait)
{
    bool retValue = false;
    DateTime dtStart = DateTime.Now;
    do
    {
        System.Threading.Thread.Sleep(sleepTime);
        if (IsBrowserLoaded())
        {
            retValue = true;
            break;
        }
    } while (((TimeSpan)DateTime.Now.Subtract(dtStart)).TotalMilliseconds < maxWait);
    return retValue;
}
public bool IsBrowserLoaded()
{
    try
    {
        return ("true" == _selObj.GetEval("((\"complete\" == selenium.browserbot.getCurrentWindow().document.readyState) && (null == selenium.browserbot.getCurrentWindow().event))"));
    }
    catch (SeleniumException selExc)
    {
        Log.Warn(DateTime.Now.ToString() + " : Selenium error encountered. " + selExc.Message);
        _selObj.SelectWindow("");
        return false;
    }
    catch (Exception exc)
    {
        throw exc;
    }
}

Monday, June 22, 2009

Selecting Popup window without Id

public bool SelectTopWindow()
{
    try
    {
        string[] arr = GetAllWindowNames();
        if (arr.Length != 0)
        {
            System.Threading.Thread.Sleep(1000);
            _selObj.SelectWindow(arr.GetValue(arr.Length - 1).ToString());
            return true;
        }
    }
    catch (Exception exc)
    {
        return false;
    }
}

Saturday, May 30, 2009

Uploading Files using Selenium RC in C#

After googling all around to overcome the Selenium incapability of handling File Upload control finally I could write a simple function in C# which will do my job. In the function given below _selObj is the object of DefaultSelenium class.

public bool TypeIntoFileUpload(string controlId, string filePath)
{
    try
    {
        string newFilePath = filePath.Replace('\\', '/');
         _selObj.WindowFocus();
         _selObj.Focus(controlId);
        string jscript="";
        jscript += "if(selenium.browserbot.getCurrentWindow().clipboardData){window.clipboardData.setData('Text','" + newFilePath + "');}";
         _selObj.GetEval(jscript);
        byte VK_CONTROL = 0x11;
        byte VK_V = 0x56;
        _selObj.KeyDownNative(Convert.ToString(VK_CONTROL));
        _selObj.KeyPressNative(Convert.ToString(VK_V));
        _selObj.KeyUpNative(Convert.ToString(VK_CONTROL));

        return true;
    }
    catch (Exception exc)
    {
        return false;
    }
}