Monday, January 16, 2012

The simple art of creating a log file for your script

Some of us will have no use for ever creating our own logs, because we use fancy environments like QTP or Test Complete that will generate pretty detailed results for our automated scripts. However, even if this is the case, there are instances where generating a log could be used as a pretty nifty debugging tool, or serve as a pretty cool sanity check for scripts that run long. Here's my basic methodology for creating a log using C# and Selenium Remote Webdriver.

[TestFixture]
public class Tests
{
     //Create a list, you will add items to the list that will become your log
     public static List<string> log = new List<string>();
     [Test]
     public void SomeTest()
     {
           //Capture the browser name and version
           string broswerName = ((RemoteWebDriver)driver).Capabilities.BrowserName);           
           string broswerVersion = ((RemoteWebDriver)driver).Capabilities.BrowserVersion);
           log.Add("Test was run on browser: " + browserName + " : " + browserVersion);
           //Log the time the test execution began
           log.Add("Test began at: " + DateTime.Now);
           //Use a stopwatch to capture times of different events.
           Stopwatch timer = new Stopwatch();
           timer.Start();
           //Do ACTION A
           log.Add("ACTION A took: " + stopwatch.ElapsedMilliseconds + "ms");
           timer.Restart();
           //Do ACTION B
           log.Add("ACTION B took: " + stopwatch.ElapsedMilliseconds + "ms");
           timer.Restart();
           //Log the time the test execution completed
           log.Add("Test ended at: " + DateTime.Now);
          //Create the file to write the log to. I want the file to always be unique, so at the end I take the date/time up to the second and strip out all the character that would cause conflict for a file name 
           string file = "name" + DateTime.Now.ToString().Replace(":", "").Replace("/", "") + ".txt"
           //Open the StreamWriter to write the log file. Create the log file, iterate through our list to populate each line of the log file. .WriteLine will start a new line.
           using (StreamWriter sw = File.CreateText("C:\\" + file ))
            {
                  for (int x = 0; x < log.Count; x++)
                        sw.WriteLine(log[x]);
            }
     } 
}

This should create a log that looks something like this:

Test was run on browser: Firefox : 8.0.1
Test began at: 01/14/2012 7:00PM
ACTION A took: 30000ms
ACTION B took: 30242ms
Test ended at: 01/14/2012 7:01PM