Friday, November 18, 2011

(Simple) Performance monitoring using Selenium Remote Web Driver (c#)

Hello all,

I wanted a simple way to monitor extremely long load times on my site. I know this isn't 100% accurate, because it really won't measure page rendering, however I find this code useful for throwing an alert when something is lost in server-side loading hell (ie A GLOBAL SEARCH!).

This code will attempt to find an element on a page you are expecting to have loaded. The while loop will not stop until that element is found. 

Note that I use XPath to find my element, however with Selenium RC you are not limited to just XPath.

using System.Diagnostics; //for the stopwatch

public static void WaitForElement(string xPath){
            bool catchFlag = false;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            while (catchFlag == false)
            {
                catchFlag = true;
                try
                {
                    driver.FindElement(By.XPath(xPath));                
                }
                catch
                {
                    Thread.Sleep(500);
                    catchFlag = false;
                }
            }
            stopwatch.Stop();
           if (stopwatch.ElapsedMilliseconds > 8000)
                  MessageBox.Show("Took too long! " + stopwatch.ElapsedMilliseconds + "ms");
}

No comments:

Post a Comment