Thursday

Selenium 2.0 / Web Driver and Eclipse



Steps to set up web driver and Eclipse:
  1. Open Eclipse from the menu choose File, New, Project...
  2. In the folder Java, choose Java Project.
  3. Give project a name, accept the rest of the defaults, and click Next.
  4. Download the latest zip file for selenium frm : http://seleniumhq.org/download/
  5. The latest version right now is : "selenium-java-2.15.0.zip"
  6. Unzip the files into the project that you just created
  7. Back in Eclipse, right click on your project in the Package Explorer and choose Build Path, Configure Build Path.... Choose the Libraries tab
  8. Click Add Jars
  9. Select all of the jars that you just unzipped into the /lib/selenium-jars/ folder and click OK
  10. Choose the primary selenium jar, which in this example is selenium-java-2.15.jar , expand and  double-click on Javadoc location. (Enter the location for the Selenium JavaDocs into the Javadoc location path field htttp://selenium.googlecode.com/svn/trunk/docs/api/java/)
  11. Click Ok and u are ready.
  12. Right click on the /src folder in your project and choose New, Package...Give the package a name and click Finish.
  13. Right click on the package and choose New, Class...Give the class a name and accept the other defaults, but make sure that public static void main(String[] args) is checked.
  14. Add code from selenium IDE in JUnit4 (WebDriver) format 
  15. Run the test :)
Happy Testing!!! 

Install m2eclipse for Indigo



Eclipse does not have integrated Maven support out of the box. To add the support, I am going to use Maven Integration (m2e).
  1. In Eclipse: Help -> Install New Software…
  2. Type the following URL in field Work with: http://download.eclipse.org/technology/m2e/releases
  3. Click Add…
  4. Give a name for the repository (such as m2eclipse)
  5. Click OK
  6. Select the checkbox Maven Integration for Eclipse
  7. Click Next etc. to move forward and choose to restart Eclipse when prompted

Wednesday

Lets Install Maven


Steps to Install Maven for Windows XP:
  1. Maven is a Java tool, so you must have Java installed.
  2. Download Maven from http://maven.apache.org/download.html#Installation
  3. Unzip the distribution archive, i.e. apache-maven-3.0.3-bin.zip to the directory you wish to install Maven 3.0.3
  4. Add the M2_HOME environment variable with the value of where you have extracted the zip artchive: C:\Program Files\Apache Software Foundation\apache-maven-3.0.3
  5. Add the M2 environment variable in the user variables with the value %M2_HOME%\bin
  6. Update/create the Path environment variable and append the value %M2% to add Maven available in the command line.
  7. Make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.5.0_02
  8. Restart the machine
  9. Open a new command prompt and type mvn --version to verify that it is correctly installed
Source: http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Happy Testing!!!

Monday

Integrate Quality Center with Fitnesse

I had a hard time trying to figure this out , so here are the steps for the basic integration of these two tools :
The same logic can be used to integrate Quality center and any open source tool:

  1. Set up a VAPI-XP-TEST in quality center that will store the script and the logic to run the same.
  2. The script would then invoke the opensource tool , in our case Fitnesse from test lab in QC.
  3. Once the test is complete we would do two things
    1. Report a Pass/Fail for the test
    2. Upload the results that are generated by the Fitnesse tool into QC
Here is the cod e that you need to place in the QC VAPI-XP-TEST:

' FitNesse.SuiteAcceptanceTests.SuiteWidgetTests.SetUpLinkTest [VBScript]
' Created by Quality Center
' ====================================================

' ----------------------------------------------------
' Main Test Function
' Debug - Boolean. Equals to false if running in [Test Mode] : reporting to Quality Center
' CurrentTestSet - [OTA COM Library].TestSet.
' CurrentTSTest - [OTA COM Library].TSTest.
' CurrentRun - [OTA COM Library].Run.
' ----------------------------------------------------
Sub Test_Main(Debug, CurrentTestSet, CurrentTSTest, CurrentRun)
  TDOutput.Clear
   '***************** VARIABLES TO BE MODIFIED **************************
  Dim strFITDatabase : strFITDatabase = "FIT"
  Dim strFITUsername : strFITUsername = "Aditya"
  Dim strFIFITassword : strFIFITassword = "pass"
  Dim strFIFITroject : strFIFITroject = "Common"
  Dim strFITTestScriptName : strFITTestScriptName = CurrentTSTest.TestName
  Dim strResultsDirectory :  strResultsDirectory = "C:\Documents and Settings\Desktop\"
  '***********************************************************************************************
  Dim WshShell, objExecObject, strOutput
  Dim strCommand, strTestTypeCommand, strRes
  Dim strTestName
  'Now setup some variables to handle to test results
  Dim strMacroName : strMacroName = "ExtractResultsFromFIT"
  Dim strExpectedResultsPath
  Dim strTimeStamp
  Dim strTemp
  'setup the timestamp in YYYYMMDD_HHMM format
  'get the year
  strTimeStamp = year(now())
  'get the month
  strTemp = month(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the day
  strTemp = day(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp & "_"
  'get the hour
  strTemp = hour(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the minute
  strTemp = minute(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the seconds
  strTemp = second(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'setup testname variable
  if strFITTestScriptName <> "" then
     strTestName = strFITTestScriptName
  end if
  'Now we can setup the expected results path
  strExpectedResultsPath = "C:\Results_" & strTimeStamp & ".html"
  'Now start setting up variables used to send the command
  if strFITTestScriptName <> "" then
      strTestTypeCommand = strFITTestScriptName
  end if
  'create a windows shell object
  Set WshShell = CreateObject("WScript.Shell")
  WshShell.CurrentDirectory = strResultsDirectory
   'construct the command we want to send to it
  'this is useful for debug purposes
  TDOutput.Print "Launching FIT with this command:"
  TDOutput.Print strCommand
 '  strCommand = "cmd /C java -jar fitnesse.jar -p 8080 -c FitNesse.SuiteAcceptanceTests.SuiteWidgetTests.SetUpLinkTest > C:\results.xml"
   strCommand = "cmd /C java -jar fitnesse.jar -p 8080 -c "&strFITTestScriptName&" > "&strExpectedResultsPath
  WshShell.run strCommand
 ' strOutput = objExecObject.StdOut.readall()
  if strOutput <> "" then
     TDOutput.Print strOutput
     'if this was a visual test, then this a playback error but we can still go on to retrieve the results
     if instr(strOutput, "Fail") <= 0 then
          If Not Debug Then
             TDOutput.Print "Test Failed to launch"
             CurrentRun.Status = "Failed"
             CurrentTSTest.Status = "Failed"
          end if
          exit sub
     end if
  end if
  'if we reach here then the test ran correctly, we can now go and retrieve the results using the excel
     if instr(strOutput, "Pass") <= 0 then
        TDOutput.Print "Test passed"
        CurrentRun.Status = "Passed"
        CurrentTSTest.Status = "Passed"
     else
        TDOutput.Print "Test Failed"
        CurrentRun.Status = "Failed"
        CurrentTSTest.Status = "Failed"
     end if
    Set objFSO = CreateObject("Scripting.FileSystemObject")
  'msgbox objFSO.FileExists(strExpectedResultsPath)
  rc = objFSO.FileExists(strExpectedResultsPath)
  msgbox rc
  If ucase(rc) <> "TRUE" then
     sleep (5)
  End If

   TDOutput.Print "Uploading results from: " & strExpectedResultsPath
  set attachF = CurrentRun.Attachments
  Set theAttachment = attachF.AddItem(null)
  theAttachment.FileName = strExpectedResultsPath
  theAttachment.Type = 1
  theAttachment.Post
    TDOutput.Print "Finished"
End Sub
Function sleep(seconds)
 Dim startTime, endTime
 startTime = Time()
 endTime = DateAdd("s",seconds,startTime)
 While endTime >= Time()
 Wend
End Function

Hope this helps everyone trying to integrate QC with other tools..
The script can be enhanced in many ways, this is just the raw version demonstarting that integration is possible.

Happy Testing!


Update:

Here is a updated code snippet for the same:

' Created by Quality Center
' 11/25/2011 5:12:37 AM
' ====================================================

' ----------------------------------------------------
' Main Test Function
' Debug - Boolean. Equals to false if running in [Test Mode] : reporting to Quality Center
' CurrentTestSet - [OTA COM Library].TestSet.
' CurrentTSTest - [OTA COM Library].TSTest.
' CurrentRun - [OTA COM Library].Run.
' ----------------------------------------------------
Sub Test_Main(Debug, CurrentTestSet, CurrentTSTest, CurrentRun)
  ' *** VBScript Limitation ! ***
  ' "On Error Resume Next" statement suppresses run-time script errors.
  ' To handle run-time error in a right way, you need to put "If Err.Number <> 0 Then"
  ' after each line of code that can cause such a run-time error.
  ' clear ouFITut window
  TDOutput.Clear
   '***************** VARIABLES TO BE MODIFIED **************************
  Dim strFITDatabase : strFITDatabase = "FIT"
  Dim strFITUsername : strFITUsername = "Aditya"
  Dim strFIFITassword : strFIFITassword = "pass"
  Dim strFIFITroject : strFIFITroject = "Common"
  Dim strFITTestScriptName : strFITTestScriptName = CurrentTSTest.TestName
  Dim strResultsDirectory :  strResultsDirectory = "C:\Program Files\Fitnesse"
  '***********************************************************************************************
  Dim WshShell, objExecObject, strOutput
  Dim strCommand, strTestTypeCommand, strRes
  Dim strTestName
  'Now setup some variables to handle to test results
  Dim strMacroName : strMacroName = "ExtractResultsFromFIT"
  Dim strExpectedResultsPath
  Dim strTimeStamp
  Dim strTemp
  Dim strPort : strPort = CurrentTestSet.TestSetFolder
  'setup the timestamp in YYYYMMDD_HHMM format
  'get the year
  strTimeStamp = year(now())
  'get the month
  strTemp = month(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the day
  strTemp = day(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the hour
  strTemp = hour(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the minute
  strTemp = minute(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'get the seconds
  strTemp = second(now())
  if len(strTemp) = 1 then strTemp = "0" & strTemp
  strTimeStamp = strTimeStamp & strTemp
  'setup testname variable
  if strFITTestScriptName <> "" then
     strTestName = strFITTestScriptName
  end if
    intLength=Mid(strTimeStamp,1,15)
   strExpectedResultsPath  = "C:\Results\" & strTimeStamp&".html"
  'Now start setting up variables used to send the command
  if strFITTestScriptName <> "" then
      strTestTypeCommand = strFITTestScriptName
  end if
  'create a windows shell object
  Set WshShell = CreateObject("WScript.Shell")
  WshShell.CurrentDirectory = strResultsDirectory
   'construct the command we want to send to it
  'this is useful for debug purposes
  TDOutput.Print "Launching FIT with this command:"
  ProcessExists ("java.exe")
if  ProcessExists ("java.exe") = True then
msgbox "FitNesse is currently running on the machine and Port is not available to run this test.",,"Warning"
TDOutput.Print "Test Failed to launch"
CurrentRun.Status = "Not Completed"
TDOutput.Print "Test Not Completed"
'CurrentTSTest.Status = "Not Completed"
exit sub
end if

  'Now run the command which will launch FIT - if nothing happens, put the command into a
  'command prompt window (start > run > "cmd") to see if there are any errors from it
  'strCommand = "cmd /C java -jar fitnesse.jar -p "&strPort&" -c "&strFITTestScriptName&"?test >" &strExpectedResultsPath
  strCommand = "cmd /C java -jar fitnesse.jar -p "&strPort&" -c "&strFITTestScriptName&"?test >" &strExpectedResultsPath
   TDOutput.Print strCommand
   WshShell.run strCommand
  Dim objFSO,objFolder,colFiles
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFolder = objFSO.GetFolder("C:\Program Files\Fitnesse\FitNesseRoot\files\testResults\"&strFITTestScriptName&"\")
  Set objFiles=objFolder.Files
      'Delete if there are any files exist in the folder
      For Each item In objFiles
        On Error Resume Next
        objFSO.DeleteFile(item)
      Next
    ' Check if the latest results file appears in the directory
  Do until objFolder.Files.Count > 0
  Loop
  For each item in objFiles
      myFileName=item.Name
      myFileName="C:\Program Files\Fitnesse\FitNesseRoot\files\testResults\"&strFITTestScriptName&"\" & myFileName
      'msgbox myFileName
      strData= LoadSchemaToArray(myFileName)
      'msgbox strData
  Next

  'if we reach here then the test ran correctly, we can now go and retrieve the results using the excel
  if instr(1,strData, "0")= 0 OR instr(1,strData, "0")= 0 then
     'msgbox  instr(1,strData, "0",1),,"0"
     'msgbox  instr(1,strData, "0",1),,"0"
     'msgbox  instr(1,strData, "0",1),,"0"
     TDOutput.Print "Test Failed"
     CurrentRun.Status = "Failed"
     CurrentTSTest.Status = "Failed"
     else
     TDOutput.Print "Test Passed"
     CurrentRun.Status = "Passed"
     CurrentTSTest.Status = "Passed"
  end if
  TDOutput.Print "Uploading results from: " & strExpectedResultsPath
  Set attachF = CurrentRun.Attachments
  Set theAttachment = attachF.AddItem(null)
  'theAttachment.FileName = myFileName
  theAttachment.FileName = strExpectedResultsPath
  theAttachment.Type = 1
  theAttachment.Post
  TDOutput.Print "Finished"
End Sub
Function LoadSchemaToArray (filename)
    Dim objFSO, strTextFile, strData, arrTags
    dim  arrXMLSchema()
    const ForReading = 1
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Open the text file  - put the whole thing into an array
    Delay(10)
    strData = objFSO.OpenTextFile(filename,ForReading).Read(260)
    'Cleanup
    Set objFSO = Nothing
    LoadSchemaToArray=strData
End Function
Function ProcessExists (ByVal strProcessName)
        Dim strFuncName:strFuncName = "ProcessExists: "
        Dim strComputer, strProcess
        Dim objService
            If Trim (strProcessName) = "" Then
                ProcessExists = FALSE
                Exit Function
        End If
        ' This statement tells to use the current machine
        strComputer = "."
        ' "winmgmts:" is used to access the root of the CIM library
        Set objService = GetObject ("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
        For Each strProcess in objService.InstancesOf ("Win32_process")
                If LCase (strProcess.Name) = LCase (strProcessName) Then
                        ProcessExists = TRUE
                        Exit Function
                End If
        Next
        ' Return
        ProcessExists = FALSE
End Function
Sub Debug2(myText)
  ' Uncomment the next line to turn off debugging
  ' Exit Sub
  If Not IsObject(objIEDebugWindow) Then
    Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
    objIEDebugWindow.Navigate "about:blank"
    objIEDebugWindow.Visible = True
    objIEDebugWindow.Toolbar = False
    objIEDebugWindow.Width = 200
    objIEDebugWindow.Height = 300
    objIEDebugWindow.Left = 10
    objIEDebugWindow.Top = 10
    Do While objIEDebugWindow.Busy
      WScript.Sleep 100
    Loop
    objIEDebugWindow.Document.Title = "IE Debug Window"
    objIEDebugWindow.Document.Body.InnerHTML = _
                 "" & Now & "
"
  End If
  objIEDebugWindow.Document.Body.InnerHTML = _
                   objIEDebugWindow.Document.Body.InnerHTML _
                   & myText & "
" & vbCrLf
End Sub
Sub Delay( seconds )
    Dim wshShell
    Set wshShell = CreateObject( "WScript.Shell" )
    wshShell.Run "ping -n " & ( seconds + 1 ) & " 127.0.0.1", 0, True
    Set wshShell = Nothing
End Sub



Thursday

VBscript to close any popup message box

A strange thing happened when i was trying to run QTP tests from Quality Center , there was this error message popped up after every test run.
Until the message box was not closed manually QC would wait indefinitely, defeating the whole purpose of automation.



So here is the vbcript that would run indefinitely waiting for the popup; and close it for tests to continue:

Set wshShell = CreateObject("WScript.Shell")
Do
      ret = wshShell.AppActivate("System Settings Change")
      If ret = True Then
          wshShell.SendKeys "%N"
          Exit Do
      End If
      WScript.Sleep 500
  Loop 

Steps to use the QTP .NET Extensibility sdk

QuickTest .NET Add-in Extensibility is an SDK package that enables you to support testing applications
that use third-party and custom .NET Windows Forms controls that are not supported out-of-the-box by the .NET Add-in.

We need to create a Custom Server (DLLs or control definition XML file) to handle each custom control.

We shall look at the steps to develop a custom server dll using the .net extensibility kit:
  1. Use the QTP Setup program to install the QuickTest Professional .NET Add-in Extensibility SDK on your computer.
  2. Create a new project in VS2008 or above and select the Visual C# > Windows node in the Project types treeVisual C# >














 3.  In the Application Settings page, specify the following settings:
  • Server class name e.g. TrackBarSrv
  • Select the Customize Record process check box.
  • Select the Customize Run process check box.
  • Accept the rest of the default settings.
4.  Click Next. The XML Configuration Settings page opens
In the XML Configuration Settings page, specify the following settings:
  •  Make sure the Auto-generate the XML configuration segment check box
  • In the Customized Control type box, enter the entire reference of the object which you can find in the references in VS for e.g. System.Windows.Forms.TrackBar
  • Accept the rest of the default settings
5.  Click Finish and in VS you will see  In the Class View window, you can see that the wizard created a class like e.g. TrackBarSrv class derived from the CustomServerBase class and an interface like ITrackBarSrvReplay interface.

6. Implement the Test Record Logic

7. Implement the Test Run Logic

8. Configure QuickTest Professional to use the Custom Server - In the Solution Explorer window, double-click the Configuration.XML fileConfiguration.XML file. Copy everything that is between and paste it in the  tag SwfConfig.xml

P.S - SwfConfig.xml file located in \dat..
Make sure that the elements contain the correct path to your Custom Server DLL

Here is the code for Trackbar.csv

using System;using Mercury.QTP.CustomServer;using System.Windows.Forms;namespace
{
[
QTCustServerReplayInterface]public interface ITrackBarSrvReplay{#region
Wizard generated sample code (commented)// void CustomMouseDown(int X, int Y);#endregion
}
void SetValue(int newValue);/// /// Summary description for TrackBarSrv.///

public class TrackBarSrv :CustomServerBase,ITrackBarSrvReplay{
// You shouldn't call Base class methods/properties at the constructor// since its services are not initialized yet.
{
public TrackBarSrv()//// TODO: Add constructor logic here//}#region IRecord override Methods#region

/// To change Window messages filter implement this method.
/// The default implementation is to get only Control's window messages.
///
public override WND_MsgFilter GetWndMessageFilter()
{
return WND_MsgFilter.WND_MSGS;
}
///
/// To catch window messages you should implement this method.
/// Please note: This method is called just in case the CustomServer is running
/// under QuickTest process.
///

public override RecordStatus OnMessage(ref Message tMsg)
{
// TODO: Add OnMessage implementation.
return RecordStatus.RECORD_HANDLED;
}
*/
Wizard generated sample code (commented)/* /// #endregion/// /// In case you extend Record process, you should add your Events handlers/// in order to listen to Control's Events.///
{
public override void InitEventListener()#region

// Adding OnMouseDown handler.
Delegate e = new System.Windows.Forms.MouseEventHandler(this.OnMouseDown);
// Adds an event handler as the first handler of the event.
// The first argument is the name of the event for which to listen.
// You must provide an event that the control supports.
// Use the .NET Spy to obtain the list of events supported by the control.
// The second argument is the event handler delegate.
AddHandler("MouseDown", e);
*/
Wizard generated sample code (commented)/* // Notice, You can add as many handlers as you need.#endregion
AddHandler(
}
Delegate e = new System.EventHandler(this.OnValueChanged);"ValueChanged", e);/// /// At the end of the Record process this method is called by QuickTest to release /// all the handlers the user added in InitEventListener method./// Please note: Handlers added via QuickTest methods are released by QuickTest infrastructure.///
{
}

{
System.Windows.Forms.
public override void ReleaseEventListener()public void OnValueChanged(object sender, EventArgs e)TrackBar trackBar = (System.Windows.Forms.TrackBar)sender;// get the new value
int newValue = trackBar.Value;// Record SetValue command to the testRecordFunction(
}
"SetValue", RecordingMode.RECORD_SEND_LINE, newValue);#endregion

#region
Record events handlers#region

{
// Record line in QTP.
if(e.Button == System.Windows.Forms.MouseButtons.Left)
{
RecordFunction( "CustomMouseDown", RecordingMode.RECORD_SEND_LINE, e.X, e.Y);
}
}
*/
Wizard generated sample code (commented)/* public void OnMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)#endregion
#endregion

#region
Replay interface implementation#region

{
MouseClick(X, Y, MOUSE_BUTTON.LEFT_MOUSE_BUTTON);
}
*/
Wizard generated sample code (commented)/* public void CustomMouseDown(int X, int Y)#endregion
{
System.Windows.Forms.
trackBar.Value = newValue;
}
public void SetValue(int newValue)TrackBar trackBar =(System.Windows.Forms.TrackBar)SourceControl;#endregion}
}
Hope this helps anyone using the extensibility! Will try and post a video if i can of the entire process!

Friday

Solution to warning in Quality Center shows FAIL


I am sure a lot of QTP users who run their tests from quality center must have noticed that a test passes with warning , but when the test set is closed it turns into fail.

Solution: The best way is to modify the registry setting or use the below code: WshShell.RegWrite"HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\"&_ "Logger\Media\TD\TreatWarningAs","TREAT_AS_PASS","REG_SZ"

If the tests are failing the key (TreatWarningAs)would have "TREAT_AS_FAIL" change this to TREAT_AS_PASS and you would be relieved for sure ;)

Hope this helps,
Happy Testing!

Wednesday

Website's underlying technology for automation


Like most testers, you probably automate a certain number of websites.. Ever wonder how those websites work? What technologies does that website or blog use? What is the underlying software that the website runs on?

These are all good questions before starting automation on a website and not always easily determined by just viewing a website.

Sitonomy is a cool web service that you can use to get information about a website, such as what technology is used to run the website, what advertising the site uses, the programming language for the website, what kind of server it is running on, and lots more.
 
 

Solution to "this test is locked by another quality center user"


There are a lot of instances while working with Quality center that you might have noticed this message "this test is locked by another quality center user”
Sometimes you may have imposed a self lock on it.. J This happens mostly when the user kills the QTP process when the script is still open(from QC).

If you have forgotten the machine where you have imposed a self lock then don’t worry as here is the soln to get rid of the same:

Copy the following code and run it from the machine were qc is instantiated.

On Error Resume Next   
desc = "Please provide the network id for the user, and please make sure" &_
        "this user is logged out prior to removing locks"   
UName = InputBox(desc,"Provide network id")  
If(UName <> "") Then     
  Set cmd = TDConnection.Command      
  cmd.CommandText = "DELETE FROM Locks WHERE LK_USER = '" & UName & "'"       
  cmd.Execute      
  MsgBox "All locks for user id: " & UName & " were removed", _       
    vbNotify+vbOKOnly,"Compelted"  
Else    
  MsgBox "No locks were changed", vbNotify+vbOKOnly, "No Info" 
End If   
On Error Goto 0

Provide your userid when prompted and wallah , the magic is done J
You can now go ahead and edit your scripts.
Happy Testing!

Thursday

Maximize browser using QTP and IE8 / IE7 / Firefox


Problem : Maximize a tabbed browser (ie7/ie8/firefox)
Solution1:  hwnd=Browser("name:=myBrowser").getROProperty("hwnd")
               Window("hwnd:="&hwnd").Maximize
Disadvantage:  Does not work with tabbed browsers consistently

Solution2: hwnd=Browser("name:=myBrowser").Object.HWND
              Set objWindow=Window("hwnd:="&hwnd2)
              objWindow.Maximize
Disadvantage:  Does not work with tabbed browsers when there are multiple browsers open
 

Solution3:
SystemUtil.Run "C:\Program Files\Internet Explorer\iexplore.exe",URL,"C:\","open","3"

The "3" at the end Activates and Maximizes the window.
Disadvantage:  Does not work when the browser is already open 


Solution4: Set WshShell = CreateObject("WScript.Shell")
               'Alt Space X - shortcut to maximize ie browser.
                WshShell.SendKeys "% x"

Hope this helps as always :)
Happy Testing!

Wednesday

Why do we need to launch the application under test (AUT) after QTP is launched?


Have you ever wondered why do we need to launch the application under test (AUT) after QTP is launched?
When I started learning QTP I asked the same question to the trainer and he said he would get back on it, after some research i found the answer to my question , sharing here what i learnt ( few years back ) and found ( recently ) :
  • QTP interacts with test applications using windows hooks.
A hook is a point in the system message-handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target window procedure.
  • Therefore these hooks help QTP during recording and identifying objects
  • Hooks can only be installed using DLLs
  • These Hooks can be injected only during runtime when QTP is brought up.
An interesting example from Tarun here :

"Hooks are basically interceptors in system". This example will clear it

User Clicks -> Windows OS determine which Application should get it -> Sends the click to the application.

Now hooks allow to intercept the message and take action accordingly

User Clicks -> Windows OS determine which Application should get it -> Installed Hook (Hook can decide to send the message or cancel it or record it or take some action based on event)->Sends the click to the application.
Happy Testing!

Ten best Open Source Bug Tracking Systems and thier Comparison


In continuation to the prev post on "Ten Best Tools for Test Automation" read another interesting link (toolsjournal) on what are the ten best open source bug tracking systems, so here is the list in no particular order:
  1. Bugzilla
  2. Mantis BT 
  3. Trac
  4. Redmine
  5. OTRS [Open-source Ticket Request System]
  6. Request Tracker
  7. Eventum
  8. BugGenie
  9. WebIssues
  10. Fossil
Click on the links to get more info on any of the tools. Happy Testing!

And if you want a comparison on the tools features here is an excellent link

Tuesday

Last friday's date using VbScript



Some vbscript to get the previous week's date, modify the code and you can do a lot of fun things with the same:

'Gets the last friday's date
 strCurrentSysDate = Date
 strModDate = dateadd("ww",-1,strCurrentSysDate)
 numWeekDay = 6- weekday(strModDate)
 strModifiedDate = dateadd("d",numWeekDay,strModDate)
 strmonth =left(monthname(month(strModifiedDate)),3)
 If len(cstr(day(strModifiedDate))) < 2 Then
  strDate = "0"&day(strModifiedDate)
 else
  strDate = day(strModifiedDate)
 End If
 strYear = year(strModifiedDate)

 strPrevDate =  strmonth& "/" & strDate & "/" & strYear
Msgbox strPrevDate

Monday

Ten Best Tools for Test Automation



Read an interesting link (toolsjournal) on what are the ten best tools for automation , though i wouldnt say that these are the ten best tools , rather they are ten known/popular tools in no particular order:
  1. QTP
  2. Watir
  3. TOSCA Testsuite
  4. Selenium
  5. VISUAL STUDIO TEST PROFESSIONAL
  6. WebUI TEST STUDIO
  7. RATIONAL FUNCTIONAL TESTER
  8. TESTCOMPLETE
  9. TESTPARTNER
  10. SOA TEST

Click on the links to get more info on any of the tools. Happy Testing!

Thursday

Allow other HP products to interact option in QTP and Launch QC explorer


 Here is the code to set "Allow other HP products" option to true before starting automation.

Set objWshShell = CreateObject("WScript.Shell")
Set objApp = createObject("QuickTest.Application")
objWshShell.RegRead("HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\")
        If Err <> 0 Then
            Wscript.Sleep 1000
            objApp.Launch
            objApp.Visible = False
            objApp.Options.Run.RunMode = "Fast"
            objApp.Quit
        End If
        objWshShell.RegWrite "HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\AllowTDConnect","1","REG_DWORD"

'------------------
' Launches QC Explorer
'------------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists ("C:\Program Files\Common Files\HP\QCExplorer\QCExplorer.exe") Then
            objWshShell.run "cmd /K CD C:\Program Files\Common Files\HP\QCExplorer\ & QCExplorer.exe http://
qc.com/qcbin/start_a.htm" 
ElseIf objFSO.FileExists ("C:\Program Files (x86)\Common Files\HP\QCExplorer\QCExplorer.exe") Then
            objWshShell.run "cmd /K CD C:\Program Files (x86)\Common Files\HP\QCExplorer\ & QCExplorer.exe http://qc.com/qcbin/start_a.htm"
Else
      Msgbox "QC Explorer not launched as .exe file not found"
End If



Happy Testing!

Test Automation Tools Comparison Matrix - Knol

Today came across an interesting comparison on test automation tools on "knol"

P.S: Click on the link to get the comparison .





Wednesday

QTP - Wait for web page to load completely



 There are instances when there isn't any unique property or object to check on the landing page during a browser navigation, in such cases we can use either of the below options to code:

set objReadyState = Browser("").Page("").Object
While objReadyState.readyState = "Completed"
Wend
Set Object=nothing


Set Object=Browser("").object
While Object.Busy=True
Wend
Set Object=nothing

Happy Testing!

Tuesday

Code to get tagnames and values from an xml


In continuation from the previous post where we try and get the attribute values from an xml, here is the code where we get the tag names and its values :


Const xmlFile1= "C:\Test.xml"
Set xmlDoc1 = CreateObject("Msxml2.DOMDocument")
xmlDoc1.load(xmlFile1)
set nodes1 = xmlDoc1.selectNodes("//*")
for i = 0 to nodes1.length -1
        tagname1 = nodes1(i).nodeName
        val1 = nodes1(i).text
        If  tagname1= "test" Then
                msgbox tagname1
                msgbox val1
                Exit for
        End If
next

Hope this helps , happy testing!

Thursday

Golden Rules for Career Success - Richard Moran


Loved this article and thought its apt for the skillset label on my blog , so here it is for the benefit of others:

WORKING as a business consultant all over the world, I have discovered some basic career-related rules that everyone should know but many don’t.

  • Business is made up of ambiguous victories and nebulous defeats. Claim them all as victories.
  • Keep track of what you do; someone is sure to ask.
  • Be comfortable around senior managers, or learn to fake it.
  • Never bring your boss a problem without some solution.
  • You are getting paid to think, not to whine.
  • Long hours don’t mean anything; results count, not effort.
  • Write down ideas; they get lost, like good pens.
  • Always arrive at work 30 minutes before your boss.
  • Help other people network for jobs. You never know when your turn will come.
  • Don’t take days off sick unless you are.
  • Assume no one can / will keep a secret.
  • Know when you do your best morning, night, under pressure, relaxed; schedule and prioritize your work accordingly.
  • Treat everyone who works in the organization with respect and dignity, whether it be the cleaner or the managing director. Don’t ever be patronizing.
  • Never appear stressed in front of a client, a customer or your boss. Take a deep breath and ask yourself: In the course of human events, how important is this?
  • If you get the entrepreneurial urge, visit someone who has his own business. It may cure you.
  • Acknowledging someone else’s contribution will repay you doubly.
  • Career planning is an oxymoron. The most exciting opportunities tend to be unplanned.
  • Always choose to do what you’ll remember ten years from now.
  • The size of your office is not as important as the size of your pay cheque.
  • Understand what finished work looks like and deliver your work only when it is finished.
  • The person who spends all of his or her time is not hard-working; he or she is boring.
  • Know how to write business letters including thank-you notes as well as proposals.
  • Never confuse a memo with reality. Most memos from the top are political fantasy.
  • Eliminate guilt. Don’t fiddle expenses, taxes or benefits, and don’t cheat colleagues.
  • Reorganizations mean that someone will lose his or her job. Get on the committee that will make the recommendations.
  • Job security does not exist.
  • Always have an answer to the question, What would I do if I lost my job tomorrow
  • Go to the company Christmas party. Don’t get drunk at the company Christmas party.
  • Avoid working at weekends. Work longer during the week if you have to.
  • The most successful people in business are interesting.
  • Sometimes you’ll be on a winning streak and everything will click; take maximum advantage. When the opposite is true, hold steady and wait it out.
  • Never in your life say, Its not my job
  • Be loyal to your career, your interests and yourself.
  • Understand the skills and abilities that set you apart. Use them whenever you have an opportunity.
  • People remember the end of the project. As they say in boxing, always finish stronger than you start.
Hope you enjoyed reading it!

Wednesday

Skillset - Test Automation Developer


In continuation of my previous posts that are tagged "Skillset" , Here is what a company is looking for when they want a "Test Automation Developer"

Overview:

The Test Automation Developer will build and execute test automation scripts using QTP, Selenium, Macro or Mobile automation test tools for functional system integration and business acceptance testing under multiple platforms and cross-browsers.

Responsibilities:

• Write automation test plans & strategies, convert & or write test scripts, perform test execution, provide result documentation & metrics reporting.
• Build automation framework in QTP
• Collaborate with Quality Assurance Analyst – subject matter expert to gather requirements for automation development and provide guidance to execution of scripts
• Provide technical knowledge on multiple projects simultaneously.
• Solid written and verbal communication skills
• Proven automation development experience
• Proficient in testing functionality of a Web and Mobile based applications.
• Must be resourceful, proactive, self-starter, able to work alone & as a team player in a dynamic environment.

Requirements:

• Software QA experience: 3 – 6 years
• Quick Test Pro (QTP) experience: 3 – 6 years
• Quality Center experience: 3 – 4 years
• Working knowledge of quality assurance methodologies and Software Development Life Cycle
• Experience building the automation frameworks in QTP
• Solid SQL skills
• Database and Back-End as well as end-to-end testing experience.
• HP QTP 10 with Web Add-on
• HP QualityCenter 10
• Selenium IDE
• VBScripting
• Descriptive Programming (Scripts from Scratch)
• SQL Server or Oracle database
• SQL Query
• VBS Macro
• MS Office.

Friday

Code to copy a test set from one folder to another in Quality Center



I am sharing this info as I had to do quite a research before i found the solution.

Problem:  Copy a test set from one folder to another in Quality Center test lab using code.

First things first: This cannot be coded in vbscript or QTP as it uses the ISupportCopyPaste interface and the CopyToClipboard method which is part of this interface. Therefore you cannot declare a statement like Dim iscp As ISupportCopyPaste

A simpler way would be to use vba and do the following:

1. Add the following code in excel vba editor.
2. Add the "OTA COM Type Library" as a reference under tools -> references from excel.
3. Run and enjoy the magic :-)

Solution:

Public Function CopyPasteTestSetFolder(sourceFolderPath, destFolderPath)
       
     strServer = "http://xyz/qcbin"
     strDomain = ""
     strProject = ""
     strUser = ""
     strPassword = ""
     
     Set objTDConnection = CreateObject("tdapiole80.TDCONNECTION")
     objTDConnection.InitConnection strServer, strDomain
     objTDConnection.ConnectProject strProject, strUser, strPassword
   
     Set objTreeManager = objTDConnection.TestSetTreeManager
     Set sourceFolder = objTreeManager.NodeByPath(sourceFolderPath)
     Set destFolder = objTreeManager.NodeByPath(destFolderPath)
   
     Dim iscp As ISupportCopyPaste
         
     Set iscp = sourceFolder

     clipboard = iscp.CopyToClipBoard(sourceFolder.NodeID, 0, sourceFolderPath)

     Set iscp = destFolder
     iscp.PasteFromClipBoard clipboard, destFolder.NodeID, 0, -1

     Set treeMng = Nothing
     Set sourceFolder = Nothing
     Set destFolder = Nothing
     Set iscp = Nothing
   
End Function


Happy Testing!

Thursday

QTP 11.0 - Patches till April 2011


Here are a set of patches that might help wrt  QTP 11.0:

QTP_00699
  • QTP 11 support for 64-Bit applications.
  • The 64-Bit technologies that are currently supported:
  • Recovery scenarios did not work in BPT wrapper tests.
  • Run-time errors were displayed if you ran a business component that contained a QCUtil.CurrentTest.Name step.
  • Function libraries that were created from an
  • QuickTest crashed or an OS blue screen appeared when using a User-Defined / Non-HLLAPI emulator on Windows 7 with Office 2007/2010 installed.
  • Testing applications in Internet Explorer when Internet
  • Explorer is in protected mode.
  • Support for Oracle Forms 11g.Enhanced support for OracleTable objects.
  • This patch adds support for testing PowerBuilder 12 applications
  • This patch adds support for testing SAP CRM 7 (a.k.a. ICWC 7, Interaction Center Web Client 7)
  • This patch installs an updated version of the .NET Add-in, providing testing support for Silverlight 2, 3 and 4.
  • This patch provides official support for testing Web applications in Firefox 3.6
http://support.openview.hp.com/downloadAPatch.jsp?patchName=QTPWEB_00063.EXE&prodName=qtp&prodRelease=11.0

QTPNET_00062

This hotfix fixes the following problems:

1. QuickTest Professional sometimes caused .Net 4 WPF applications with multiple AppDomains to crash.

2. QuickTest Professional sometimes caused an error message to be displayed by the application when

spying on a specific WPF combo box.

QTPNET_00066

1. This hotfix enables a custom server to instruct QuickTest Professional  to assign a logical name to a test object by implementing a 'logical_name' property defined in its CustomPropInterface.

2. This hotfix enables a custom server to define run methods that include optional parameters by tagging the parameters with the [Optional] attribute. To do this, the argument element's IsMandatory attribute needs to be set to 'false' in the test object configuration file.
 
3. Prior to this hotfix, QuickTest would sometimes ignore the return value of a custom server's IsKnownPartOf method when applied to a combo box child.

4. Prior to this hotfix, QuickTest would sometimes load into the application all the assemblies in the folder containing the custom server dll.

Monday

VBScript Code beautifier / Formatter


For a long time was looking for some tool that would quickly format the vbscript files that I had. Here is an amazing tool that will help you do the same:

Both the source code and the exe are available for download from here:VBSBeautifier - Daan Systems

Features:

· Comes with a nice GUI.
· Works on serverside and clientside VBScript.
· Can be used as a text filter in editors.
· Skips HTML.
· Properizes keywords.
· Splits Dim statements.
· Places spaces around operators.
· Indents blocks.
· Lines out assignment statements.
· Removes redundant endlines.
· Makes backups.

Thursday

Selenuium and Cucumber



Since both Selenium and Cucumber are my fav tools , Found an interesting deck on slideshare titled : "Using Selenium and Cucumber to test a Healthcare Information System"

This was presented at the Selenium Conference April 2011 - San Fransisco by Andy Tinkham. 

Here is the link to download the same.

Wednesday

FizzBuzz


 
Try solving this very simple program which is asked in many interviews, especially to testers who use a lot of scripting in automation:

  • Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and For the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”
This is also a game played in the pubs , where players generally sit in a circle. The player designated to go first says the number "1", and each player thenceforth counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates or makes a mistake is either eliminated or must pay a forfeit, such as taking a drink.


 Most tester's who know to code are not able to solve this simple problem. Out of every ten automation engineers i have interviewed 9 weren't able to solve this simple problem.

---------------------------------------------------------------------------------------------------------------
Lets look at the simple algo:

For n = 1 To 100
 Select Case 0
   Case n Mod 15
      f = "FizzBuzz"
   Case n Mod 3
      f = "Fizz"
   Case n Mod 5
      f = "Buzz"
   Case Else
      f = n
 End Select
 Print f
Next n

Tuesday

Browse from VBScript


 Something very simple yet complicated is trying to get a browse dialog using vbs.
So here is a snippet that will help in adding a Browse dialog like in the pic , instead of a message box asking for the absolute/relative path of the folder:

Const EDITBOX = &H10
Const DIALOGSTYLE = &H40
Set objShell = CreateObject("Shell.Application")
Set objFolder= objShell.BrowseForFolder(0, "My Computer:",EDITBOX Or DIALOGSTYLE)

Browse = objFolder.Items.Item.path
If Err.Number > 0 Then
    MsgBox("You have not selected a folder." & vbCrlf & "This script will not continue!")
    Err.Clear 
Else
    wscript.echo Browse
End If

Hope this helps!

Thursday

Quick Overview on Agile Scrum


Before we do more Scrum, we should know what is Agile:
What is Agility?
Values, principles and practices that foster team communication and feedback to regularly deliver customer value through working software.”
 

  • Team communications - Concentrate more on communication and collaboration rather than process and tools 
  • Feedback - lots and lots of daily feedback with all stake holders involved - 
  • Regularly Deliver - Software releases every quarter with internal releases weekly or bi-weekly
  • Value - Focus on highest valued features first
  • Working Software - Focus on getting S/W working early and keeping it releasable rather than big-bang waterfall approach 
Agile Values 
  • Emphasize face-to-face communication over written documents.
  • Agile teams are located in a single open office sometimes referred to as a bullpen.
  • Highlight working software as the primary measure of progress. 
  • Produce very little written documentation relative to other methods 

What are the Agile methods ?
  • SCRUM
  • Adaptive Software Development - replaces the traditional waterfall cycle with a repeating series of speculate, collaborate, and learn cycles.
  • Crystal - contains the following properties frequent Delivery of Usable Code to Users , reflective Improvement.
  • Dynamic System Development Method (DSDM) - Its goal is to deliver software systems on time and on budget while adjusting for changing requirements along the development process.
  • Extreme Programming - it advocates frequent "releases" in short development cycles (timeboxing), which is intended to improve productivity and introduce checkpoints where new customer requirements can be adopted.
  • Feature Driven Development (FDD) –At start of project: Develop an Overall Model, Build a Features List, Plan by FeatureWithin each iteration: Design by Feature, Build by Feature
Scrum - Introduction
  • Scrum (an abbreviated form of scrummage), in the sports of rugby, is a way of restarting the game, when the ball has gone out of play.
  • Scrum is an iterative incremental framework for managing projects.
  • Focuses on managing systems with changing requirements
  • The goal is to deliver as much quality software as possible within a series of short intervals. 
Scrum - Process
 Sprint
  • Scrum projects make progress in a series of “Sprints”
  • Timeframes are called Time-boxes (typically 2 – 4 weeks)
  • Every Sprint team does the following: Analysis -> Design -> Code ->Test
  • At the end of each Sprint, the Team must produce a potentially shippable product increment.
Scrum Framework 
  1. Roles : Product Owner, Scrum Master, Team
  2. Artifacts : Product Backlog, Sprint Backlog, and Burndown Chart
  3. Ceremonies : Sprint Planning, Sprint Review, Sprint Retrospective, & Daily Scrum Meeting  
Product Owner
 

  • Represents (or is) the user or customer for the project.
  • Defines goals for the overall project
  • Knowing what to build and in what sequence
  • Defines and Prioritizes Features
  • Set length of calendar time for Sprint
    • Typically 2-4 weeks
    • Does not interfere with Sprint (no scope creep)
    • Release dates. Accepts or rejects work.
 Scrum Master
  • Supports the Team
  • Facilitates the Daily Scrum meeting. Asks each developer:
    • What did you do yesterday?
    • What are you doing today?
    • What is in your way?
  • Listens and watches carefully during Scrum meeting
  • Secures resources if needed
  • Communicates to Product Owner
Scrum Team
  • Typically 5-10 people
  • Cross-functional - QA, Programmers, UI Designers, etc.
  • Members should be full-time/dedicated
  • Teams are self-organizing
  • Members can change only between sprints 
Scrum’s three Artifacts
Product Backlog :
  • Requirements
  • A dynamic list of all that is desired to work on the project
  • Prioritized by the Product Owner based on business value
  • Reprioritized at the start of each Sprint
  • Each feature has an associated estimate, provided by the ACTUAL team who will do the work
  • High priority features are split into “stories” achievable within an iteration.
  • Each “story” is prioritized and scoped.
  • Prioritized based on business value (Very High, High, etc.) by the Product Owner. 
Sprint Backlog :
 
  • A subset of Product Backlog Items, which define the work for a Sprint 
  • Usually has more details including planned hours and primary person responsible to do the work during the Sprint 
  • Is created ONLY by Team members 
  • Should be updated every day 
  • If a task requires more than 16 hours, it should be broken down 
  • Team can add or subtract items from the list. Product Owner is not allowed to do it
 
Sprint Burndown Chart:
  • Provides visibility into the Sprint 
  • Demonstrates progress by the team 
  • Work on the Horizontal, Time on the Vertical 
  • Depicts the total Sprint Backlog hours remaining per day. 
  • Ideally should burn down to zero to the end of the Sprint 
  • It is never a straight line. 
Scrum’s three ceremonies:
 
Sprint Planning Meeting:
 
  • Product Owner reviews: Vision, Roadmap, Release Plan 
  • Team reviews: Estimates for each item on Backlog that is a candidate for the Sprint
  • Team pulls the work: From the Product Backlog onto the Sprint Backlog
Daily Scrum Meeting 
  • Short (15 - 30 min) frequent meetings, facilitated by the Scrum Master
  • All team members attend
  • One activity – Scrum Master asks each attendee 3 questions 
  • Both Chickens and pigs are invited 
  • Only pigs can talk
Sprint Review Meeting 
  • Team presents what it accomplished during the sprint 
  • Typically takes the form of a demo of new features or underlying architecture 
  • Informal  2-hour prep time rule 
  • Starts with: Product Demo Led by Product Owner 
  • Ends with: Sprint Retrospective Led by Scrum Master
    •What worked?
    •What didn’t?
    •What adjustments can we make now?
What is a User Story? 
 
  • Short descriptions of features that need to be coded and tested
  • Simple requirements
  • Generally written on 3X5 index cards 
  • Form: As [a type of user] I want to [perform a specific action] such that [result]
  • Example: “As a web user, I want to
    • Make safe searches, such that I may
    • have filtered search results”
  • Stories that are big are called EPICS