Monday, June 28, 2010

QTP Interviews : Tips

QTP is the buzz word in testing industry, and a decent experience in QTP, should land you decent jobs if Test Automation is your area.
However as always, there are certain things to be taken care, when attending the QTP interview, below are my insights especially as i have been conducting interviews for the past three years.

1 : Questions depends on the experience summary
2 : Questions vary for 1+, 3+ , 5 + experience candidates, so be mindful of the amount of experience to be noted if you are not confident on some concepts.

I have classified the skillsets in Jr, Med and Sr levels but this does not consider those who would like to be Auto consulatants.

3: Some factors looked upon for a junior Automation Engg ( 1+)
         Clear understanding of Basic concept
          Automation Tool features
          Pin Point navigation of Options and Settings
          Passion and keenness to learn and explore new things
          Be sure to point any extra Automation tasks you have carried out other than project assignments, this
defines your interest into the area.
          Accurate syntax of commonly used statements

4. Some factors for medium level Auto Engg, In addition to above skill sets, these candidates should be equipped to handle questions on:
         Clear with need for Automation
         Info on other tools and why QTP scores over others
         Ability to review and prepare deliverables other than scripts
         Best practices information
         Framework Defintion

5. Finally, there are not many to be called as Automation experts, but for Senior Auto Engg
         Framework defintion and how to chose one, factors that define the choice
         Ability to build Auto process from nothing
         Strong information on alternate Auto mechanism and hold on some of them
         Industry standards
         Effective and Effecient Automation
         Balance Technical information with sound process knowledge
         Sound Estimation and ROI calculating mechanism

Automation consultants are more of one man army, who should and is expected to posses knowledge on every aspect of the tool and Automation in general, would be coming up with a different thread on them

Wednesday, June 23, 2010

Not able create/view Function Library

One among many known issues of QTP, some common workarounds:
  • In previous versions(below V9.5) is to re-register all assicated Dll's by executing 'quicktestprofessional.bat' file located in the bin 'directory'.
  • Post 9.5, the batch file no more available.
  • Navigate to Tools/Options , click on Restore Defaults to reset all the tab configuration.
  • Usually occurs when LoadRunner is installed on the same machine. There is no patch available yet, but a open defect is logged with HP, refer link below:
  • http://forums11.itrc.hp.com/service/forums/questionanswer.do?admit=109447626+1277274987957+28353475&threadId=1372138
  • Either Repair the install, reinstall the tool is the only solution as of now.

Monday, June 21, 2010

Parse QTP Report XML

'Parse QTP report xml, when required to convert into other file types
'Source : SQA Forums Post
'http://www.sqaforums.com/showflat.php?Cat=&Board=UBB20&Number=626183

*************************************************************************

Function parseQtpXmlResultFileExample()
Const XMLDataFile = "C:\Documents and Settings\Desktop\TestQTP\Res1\Report\Results.xml"

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)

'Get test name:

Set TcNode = xmlDoc.SelectSingleNode("/Report/Doc/DName/text()")
MsgBox "Test case name:" &TcNode.NodeValue

Set node = xmlDoc.SelectSingleNode("/Report/Doc/NodeArgs/Disp/text()")

'Get product name:
Set node = xmlDoc.SelectSingleNode("/Report/Doc")
MsgBox node.GetAttribute("productName")

'Get Summary - sTime
Set node = xmlDoc.SelectSingleNode("/Report/Doc/Summary")
MsgBox node.GetAttribute("sTime")


''Get Summary - passed
Set node = xmlDoc.SelectSingleNode("/Report/Doc/Summary")
strPass = node.GetAttribute("passed")

MsgBox "Pass verification: " & strPass

'Get Summary - passed
Set node = xmlDoc.SelectSingleNode("/Report/Doc/Summary")
strPass = node.GetAttribute("passed")

MsgBox "Pass verification: " & strPass

End Function

*************************************************************************

call parseQtpXmlResultFileExample()

Tuesday, June 8, 2010

Testing Team Expectations

As a prelude to series of Articles on Test Process, Roles and Responsibility definition is very critical, Starting the series of with the article on Automation Lead:

Some of the main items expected :

Analyse and Understand Project/System requirements
Perform POC to assess the Automation feasibility
Prepare Automation Approach/Plan
Publish Automation Estimate and projected ROI
Desgin/Customize Automation framework
Review Manual test cases for Automation readiness
Coordinate with system test lead on Automation assistance(ex : Test case clarifications and Test Bed set up)
Construct and Review Scripts
Validate and Report Automation Results/Findings
Track Defects detected through Automation through closure, Plan for re-run of scripts.
Sign Off Automation Test Execution
Calucate ROI
Participate in all project meetings/discussions

Friday, June 4, 2010

OTA - Add Attachments into QC

'TestName The name of the test where the attachment needs to be saved
'LocalFilePath The path to the document that needs to be uploaded
'FileDescription A description of the document, stored in the description field
'TestObj : QC Object that is created.

**************************************************************************

Public Sub SaveAttachmentToTestObj(TestObj, LocalFilePath, FileDescription)
Set Attachments = TestObj.Attachments
Set Attachment = Attachments.AddItem(Null)
Attachment.FileName = LocalFilePath
Attachment.Description = FileDescription
Attachment.Type = 1'TDATT_FILE
Attachment.Post ' Commit changes
End Sub

' This function saves an attachment to the current test (the test must be existing on TestDirector).
' LocalFilePath: Path indicating the location of the attachment on the local filesystem
' FileDescription: Description of the file (Description field on TestDirector)

Public Function SaveAttachment(LocalFilePath, FileDescription)
SaveAttachmentToTestObj QCUtil.CurrentRun, LocalFilePath, FileDescription
End Function

**************************************************************************

OTA - Download Manual Test Case

QC being one of the widely used tool in Test Management, upload/download test cases into QC is a part of Tester daily routine.

There are multiple ways to create a Test case in QC:
Add manual test cases in Test Plan
Upload Test cases from MS Excel using QTP-Excel Add-in
Upload Test cases from custom file into QC using OTA

Similarly during project migration, archiving test cases is very critical, which can be accomplished in multiple ways:
Using QC project archive tool
Download one test cases at a time by using the Save-As feature
Create a HTML report of all test cases within a folder
Use OTA to write a plug in to download the test cases within folder or set of folder

Below is the sample usage of the last option described above.
The script is written based on QC-API OTA, which exposes the features of QTP and everything done manually on UI of QC can be accomplished through OTA.

A very powerful tool in the hands of Automation tester with an inclination towards simplifying things by getting hands a bit dirty

PS : An article on OTA is due, so look out there for more information on OTA

'*************************************************************************' ' DownLoad Tests From QC and Store in Local Disk. Specify the folder path in QC Test Plan and the local disk path where the scripts needs to be stored
'26/01/07

'**************************************************************************

'Code to redirect the error into file is missing

Dim td
Dim tstMgr 'As TestManager
Dim tsttr 'As TestPlan Folder
Dim tsetFact 'As TestSetFactory
Dim tsetList 'As List

On Error Resume Next

'Create TD/QC Object and Connect and Login to the same

Set td=createobject("TDApiOle80.TDConnection.1")
td.InitConnectionEx "http://QC address"
td.ConnectProjectEx "Domain", "Project", "UserId", "Pwd"

If QCUtil.IsConnected Then

Set tstMgr = td.TreeManager

' Specify the Folder path of the tests that should be downloaded.

Set tsttr = tstMgr.NodeByPath("Subject\Application Product Test")
Set tsetFact = tsttr.TestFactory
Set tsetList = tsetFact.NewList("")

' Specify the Folder path of the tests where the scripts should be downloaded.
localTstPath = "C:\BackUp"

' Specify the test case that needs to be downloaded to the local disk
strTest = Inputbox("Enter test case name")

For Each tset in tsetList

tstName = tset.Name
If strTest = tstName Then
localTstPath = localTstPath & "\" & tstName
Set ext = tset.ExtendedStorage
ext.ClientPath = localTstPath
ext.ServerPath = tset.FullPath
ext.Load "-r *.*", True
Exit For
End If

' Specify the Folder path of the tests where the scripts should be downloaded.

localTstPath = "C:\BackUp"

Next

End If
************************************************************************
' Served the purpose? Share your feedback
** Happy Automating **

Mercury Custom Objects 2 - "Mercury.ProcValues"

'Usage of Mercury Custom Objects
'Retrive process memory usage using reserved objects
'Source : Unknown

***********************************************************************
' Create the "Mercury.ProcValues" object

Set MyProcess = CreateObject("Mercury.ProcValues")

process = "Notepad"

MsgBox MyProcess.GetProcessValues(process, "MemUsage")

' Using "With"
With MyProcess
MsgBox .GetProcessValues(process, "BasePriority")
'---------------------------------------------------------------
MsgBox .GetProcessValues(process, "CPUTime")
'---------------------------------------------------------------
rc = .GetProcessValues(process, "Modules")
' Write modules list to file as the returned value is very large:
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\Modules.txt", 2, True)
f.Write rc
f.Close
'---------------------------------------------------------------
MsgBox .GetProcessValues(process, "VMSize")
End with

Set MyProcess = NOTHING
'---------------------------------------------------------------

Wscript- Retrieve Process Memory Usage

'Retrieve all memory usage of a particular process currently active n a system using Windows Script
'Source : MSDN
'02/06/2006

**************************************************************************

Sub retrieveMemoryUsage(Exe_Name)

'On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"&Exe_Name&"'")
For Each objProcess in colProcessList
'objProcess.Terminate()
'msgbox objProcess.ProcessId
var = objProcess.WorkingSetSize
msgbox int(var/1024) &" K"
Next

End Sub

retrieveMemoryUsage("Rtvscan.exe")

**************************************************************************

Wscript : Retrieve System Parameters

'Retrieve all process information currently on a system using Windows Script
'Source : MSDN
'02/06/2006

*************************************************************************
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId = 0",,48)
For Each objItem in colItems
Wscript.Echo "Caption: " & objItem.Caption
Wscript.Echo "CSName: " & objItem.CSName
Wscript.Echo "ExecutablePath: " & objItem.ExecutablePath
Wscript.Echo "Handle: " & objItem.Handle
Wscript.Echo "HandleCount: " & objItem.HandleCount
Wscript.Echo "Name: " & objItem.Name
Wscript.Echo "OSCreationClassName: " & objItem.OSCreationClassName
Wscript.Echo "OSName: " & objItem.OSName
Wscript.Echo "PageFaults: " & objItem.PageFaults
Wscript.Echo "PageFileUsage: " & objItem.PageFileUsage
Wscript.Echo "PeakPageFileUsage: " & objItem.PeakPageFileUsage
Wscript.Echo "PeakVirtualSize: " & objItem.PeakVirtualSize
Wscript.Echo "PeakWorkingSetSize: " & objItem.PeakWorkingSetSize
Wscript.Echo "Priority: " & objItem.Priority
Wscript.Echo "PrivatePageCount: " & objItem.PrivatePageCount
Wscript.Echo "ProcessId: " & objItem.ProcessId
Wscript.Echo "QuotaNonPagedPoolUsage: " & objItem.QuotaNonPagedPoolUsage
Wscript.Echo "QuotaPagedPoolUsage: " & objItem.QuotaPagedPoolUsage
Wscript.Echo "QuotaPeakNonPagedPoolUsage: " & objItem.QuotaPeakNonPagedPoolUsage
Wscript.Echo "QuotaPeakPagedPoolUsage: " & objItem.QuotaPeakPagedPoolUsage
Wscript.Echo "SessionId: " & objItem.SessionId
Wscript.Echo "Status: " & objItem.Status
Wscript.Echo "ThreadCount: " & objItem.ThreadCount
Wscript.Echo "UserModeTime: " & objItem.UserModeTime
Wscript.Echo "VirtualSize: " & objItem.VirtualSize
Wscript.Echo "WorkingSetSize: " & objItem.WorkingSetSize
Wscript.Echo "WriteOperationCount: " & objItem.WriteOperationCount
Next

*************************************************************************

QC-Download QTP Scripts

' Script to download QTP test from QC and save into local disk
'05/02/2006
'Does not use extended storage offerred by QC, which can be another way to do the same

***************************************************************************
Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtUpdateRunOptions 'As QuickTest.UpdateRunOptions ' Declare an Update Run Options object variable
Dim qtRunResultsOptions 'As QuickTest.RunResultsOptions ' Declare a Run Results Options object variable
Dim blsSupportsVerCtrl ' Declare a flag for indicating version control support
Dim td As New TDConnection
Dim tstMgr As TestSetTreeManager
Dim tsttr As TestSetFolder
Dim tsetFact As TestSetFactory
Dim tsetList as List


strTargetPath = CreateInputDialog ("Enter the Target Script Path")

strQCFolderPath = CreateInputDialog ("Enter the QC Folder Path that contains Tests")

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
qtApp.Launch ' Start QuickTest
qtApp.Visible = True ' Make the QuickTest application visible


' Make changes in a test on Quality Center with version control
qtApp.TDConnection.Connect "http://tdserver/tdbin", _ "MY_DOMAIN", "My_Project", "UID", "Pwd", False ' Connect to Quality Center

If qtApp.TDConnection.IsConnected Then ' If connection is successful

blsSupportsVerCtrl = qtApp.TDConnection.SupportVersionControl ' Check whether the project supports vervion control

'Retrive all the Test from QC and Save them to Local Disk

Set tstMgr = td.TestSetTreeManager
Set tsttr = tstMgr.NodeByPath("Path\Test")
Set tsetFact = tsttr.TestSetFactory
Set tsetList = tsetFact.NewList("")
For Each tset in tsetList

' Msgbox tset.Name

qtApp.Open "[QualityCenter] Subject\tests\test1", False ' Open the test

If blsSupportsVerCtrl Then ' If the project supports version control
qtApp.Test.CheckOut ' Check out the test
End If

' Prepare the UpdateRunOptions object

Set qtUpdateRunOptions = CreateObject("QuickTest.UpdateRunOptions") ' Create the Update Run Options object
' Set the Update Run options: update the Active Screen and test object descriptions. Do not update checkpoint values
qtUpdateRunOptions.UpdateActiveScreen = True
qtUpdateRunOptions.UpdateCheckpoints = False
qtUpdateRunOptions.UpdateTestObjectDescriptions = True



' Prepare the RunResultsOptions object
Set qtRunResultsOptions = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtRunResultsOptions.ResultsLocation = "" ' Set a temporary results location



'Save the Open Test into Target Path Specified
qtApp.Test.SaveAs targetQTPscriptPath



If blsSupportsVerCtrl And qtApp.Test.VerCtrlStatus = "CheckedOut" Then ' If the test is checked out
qtApp.Test.CheckIn ' Check it in
End If

Next
qtApp.TDConnection.Disconnect ' Disconnect from Quality Center

Else

MsgBox "Cannot connect to Quality Center" ' If connection is not successful, display an error message.

End If

'Exit QuickTest

qtApp.Quit
Set qtApp = nothing

***************************************************************************

Windows : System Unlock

Automation testing during application idle time may get affected if the system locks.
There are many ways in preventing the same, one would be pass a keyboard event at regular intervals.

PS: Take care the key pressed does not any impact on the script run.

*************************************************************************
'Pass Numlock key evnet every 10 sec
'To get the keywords for other keys refer MSDN site

set WshShell = WScript.CreateObject("WScript.Shell")
Dim i
i = 11
MsgBox i
While i > 10
WshShell.SendKeys "{NUMLOCK}"
WScript.Sleep 10000
i = i + 1
Wend

*************************************************************************
'Post assisted, you were looking for something else, write back
** Happy Automating**

Windows : System Restart

'Restart windows machine
'Source MSDN
'04/06/2010

*****************************************************************

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Shutdown)}!\\" & _
strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Reboot()
Next
*****************************************************************

IE-DOM -GetVersion

'Get the version of IE currently installed on your local machine.
'Source MSDN
' 04/06/2010

**********************************************************************
strVersion = BrowserVersion

MsgBox strVersion

Function BrowserVersion

'String variable to hold the computer name
Dim strComputer
'String variable to hold the Registry key reference
Dim HKEY_LOCAL_MACHINE
'Registry object
Dim oReg
'String variable to hold the registry key path
Dim strKeyPath
'String variable to hold the registry key path
Dim strValueName
'String variable to hold the registry key value
Dim strValue
'Place Holder
Dim arrTmp

HKEY_LOCAL_MACHINE = 2147483650
strComputer = "."

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Internet Explorer"
strValueName = "Version"

oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

If Instr(strValue," ") Then
arrTmp = split(strValue, " ")
BrowserVersion= arrTmp(0)
Else
BrowserVersion=strValue
End If

End Function

**********************************************************************

Thursday, June 3, 2010

QTP & Environment Variables

A mode of parameterization, but using usage of Env variables is choice made during the framework definition.

Alternatively it is global variable defined either within or outside the scope of QTP. Read on how the above two differ.

Environment variables can be of two types in general:
System Defined (Built - In)
User Defined

The first class is usually read only variables, where as the second one's are User specific.

However when it comes to QTP, there can be env variables within the scope of QTP, used for parameterization, but system environment variables
which are used to control the software’s and operations of the local machine can also be accessed through this mode.

Environment tab is under File/Test Settings menu in QTP.
Users can create their own variables which would be local to the scope of the test being defined in.
The same variables can be accessed from the script as below:

Environment.value("varName") 'to create variables at run time.
Environment("varName") 'if variable is already defined

Built In variables can be accessed in the same way as above:
Environment("TestName")

Alternative users can create an external xml file and load the values into the system at runtime.
However the variables would be read only and cannot be edited during script run.

Command to perform the same in script is:
Environment.LoadFromFile("FullFilePath")

When required to pass values between applications during /after the test run, this comes in handy.
Using system or user environment variables makes sure the values are available for any application post the test run.
For a novice QTP user updates to this variable can be easy when compared to the QTP environment variables.


Sample Usage as below:

*************************************************************************

'Function to retrieve the value of the DSN from the system variable and use the same for all Database Checkpoints.
'System Variable "DSN" should be created and the should contain the connection string for mcdb98.
'Sample Connection string : DSN=aaaa;NLN=Winsock;NA=11.11.11.11,6000;DB=aaaa;UID=readonly;PWD=readonly
'Change only the instance of DB or the entire network path.

Function EnvironmentVar(DSN)
Dim WSHShell
Set WSHShell = CreateObject("WScript.Shell")
DSN = WSHShell.Environment.item("DSN")
Environment.Value("DSN") = DSN
Set WSHShell = Nothing
End Function

*************************************************************************
' You liked the post, looking forward to your feedback
** Happy Automating **

Mercury KB3 - Usage of Dictionary Objects

Problem Description: How to use the Dictionary object
The Dictionary object can be used as an alternative to using environment variables when sharing values between Actions. The Dictionary object allows the user to assign values to variables that are accessible from all Actions (local and external) in the test in which the Dictionary object is created.
________________________________________
Solution: Create a Dictionary object to access the Dictionary methods
Use CreateObject to create an object reference to the Dictionary object ("Scripting.Dictionary"), then call the methods as needed.
Dictionary Object Methods:
• To add a value to a Dictionary object use the Add method.
object.Add(key, item)
object The name of the Dictionary object.
key The key associated with the item being added. Similiar to an index of an array.
item The item associated with the key being added. In other words, the value being assigned to the key.
In the following example, the Dictionary object is named v. The string (item) "Hello" is assigned to the key "value1."
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
• To retrieve an item(value) from a Dictionary object use the Item method.
object.Item(key)
object The name of the Dictionary object.
key The key of the value that is retrieved.
In the following example, the Item method is used to view the item (value) associated with the key named "value2" of the Dictionary object v.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
msgbox v.Item("value1")
• To retrieve a collection of all the items in a Dictionary object and place into an array, use the Items method.
Note:
The previous Item method will retrieve one item. The Items method will retrieve a collection of items.
object.Items
object The name of the Dictionary object.
In the following example, the Items method will return all the items in Dictionary object v and place them in an array named myArray. The items(values) can be viewed by iterating through the array in the For-Next loop.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
v.Add "value2", "Goodbye"
v.Add "status", "PASS"
myArray = v.Items
For i=0 to v.Count - 1
msgbox myArray(i)
Next
• To verify if a key of a Dictionary object exists, use the Exists method.
object.Exists(key)
object The name of the Dictionary object.
key The key value for which you are searching.
In the following example, the Exists method is used to verify if the key "value3" exists in the "v" Dictionary object.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
v.Add "value2", "Goodbye"
v.Add "status", "PASS"
If v.Exists("value3") Then
msgbox "The key exists"
Else
msgbox "The key does not exist"
End If
• To return an array containing all of the keys of a Dictionary object, use the Keys method.
object.Keys
object The name of the Dictionary object.
In the following example, the Keys method will return all the keys in Dictionary object v and place them in an array named myArray. The keys can be viewed by iterating through the array in the For-Next loop.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
v.Add "value2", "Goodbye"
v.Add "status", "PASS"
myArray = v.Keys
For i=0 to v.Count - 1
msgbox myArray(i)
Next
• To remove a key and its associated item from a Dictionary object, use the Remove method.
object.Remove(key)
object The name of the Dictionary object.
key The name of the key that will be removed from the Dictionary object.
In the following example, the "status" key and its associated value, "PASS," will be removed from the "v" Dictionary object.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
v.Add "value2", "Goodbye"
v.Add "status", "PASS"
v.Remove("status")
• To remove all of the keys and associated items from a Dictionary object, use the RemoveAll method.
object.RemoveAll
object The name of the Dictionary object.
In the following example, all of the keys and associated items will be removed from the "v" Dictionary object.
Example:
Set v = CreateObject("Scripting.Dictionary")
v.Add "value1", "Hello"
v.Add "value2", "Goodbye"
v.Add "status", "PASS"
v.RemoveAll

You can also create a reserved test object for the Dictionary object. This will also allow you to share data between actions in a test. To do this, you must add it to the reserved object section of the registry.
1. Open Window's registry by opening a Run window and entering regedit.
2. Navigate to HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects.
3. Create a new key (folder) named GlobalDictionary by right-clicking on the ReservedObjects key and selecting New -> Key.
4. Under the new key, create a String value named ProgID by right-clicking on GlobalDictionary and selecting New -> String Value.
5. Assign "Scripting.Dictionary" to the new ProgID string value by right-clicking on ProgID and selecting "Modify."
Example:
GlobalDictionary.Add "a", "Athens"
msgbox GlobalDictionary.Exists("a")
GlobalDictionary.Remove("a")

FSO- Delete Cookies

'Delete Cookies for all users in your local disk
'Enahnces the script performance before each run instance
'Usage of fso
'Admin rights requiredto access other users profile

'Type : 1
**********************************************************************

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFolder = fso.GetFolder ("C:\Documents and Settings")
Dim delCookies
For Each oUserFolder In oFolder.SubFolders
If fso.FolderExists (oUserFolder.Path & "\Cookies") Then
Set oCookies = oUserFolder.SubFolders("Cookies")
Set oCookieFiles = oCookies.Files
iCount = oCookieFiles.Count
ReDim delCookies(iCount - 1)
i = 0
For each oFile in oCookieFiles
Set delCookies(i) = oFile
i = i + 1
Next
For i = Lbound(delCookies) to UBound(delCookies)
If delCookies(i).name <> "index.dat" Then
delCookies(i).delete
Set delCookies(i) = Nothing
End If
Next
End If
Next

Set oFolder = Nothing
Set fso = Nothing

**********************************************************************

Type 2 : Using WScript

**********************************************************************

set FSO = createobject("scripting.filesystemobject")
set oSHELL = createobject("wscript.shell")
strProfile = oShell.expandenvironmentstrings("C:\Documents and Settings\A032231")
set ieTemp = FSO.GetFolder(strProfile & "\Local Settings\Temp").files
set ieTempIntFiles = fso.GetFolder(strProfile & "\Local Settings\Temporary Internet Files").Files
set cookies = fso.GetFolder(strProfile & "\Cookies").files
call killFiles(ieTemp)
call killFiles(ieTempIntFiles)
call killFiles(cookies)

sub killFiles (Files)
for each obj in Files
set files = fso.getfile(obj)
If NOT files.name = "index.dat" then
obj.Delete (force)
End if
next
end sub

set FSO = nothing
set oShell = nothing
set userProfile = Nothing
set ieTempIntFiles = Nothing
set cookies = Nothing

**********************************************************************

** Happy Automating **

Excel COM - 4- Convert .csv to .xls

' CSV to XLS conversion
'Reference HP-Merucury QTP KB 10941 , for conversion of any delimited file to other.

In the code below,
Change the second and third lines to point the variables to the actual folders you want
Save this code in a file with .vbs extension
Execute this vbs file at a suitable point in your code when you need the xls file instead of a csv file.

Dim folderWithCsvFiles, folderExcelFilesGoInto
folderWithCsvFiles = "C:\myDataFolder\"
folderExcelFilesGoInto = "C:\"

Set appExcel = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderWithCsvFiles)
Set fc = f.Files
For Each f1 in fc
fileName = f1.name
loc = Instr(1, fileName, ".csv", 1)
If loc > 0 Then
appExcel.Workbooks.Open(folderWithCsvFiles & fileName)
nameLength = Len(fileName)
newFileName = Mid(fileName, 1, (loc-1)) & ".xls"
appExcel.ActiveWorkbook.SaveAs folderExcelFilesGoInto & newFileName, 43 ' 43 is the code for xls format
appExcel.Workbooks.Close
End If
Next
appExcel.Quit
Set appExcel = Nothing
Msgbox("Done converting the files") ' you omit this line if you are not manually checking that this code is executed

QTP-UtilityObjects-1- ClipBoard

HP-Mercury provides a suite of utility objects which can be used as per the need.
One example is the use of ClipBoard object.
If the Test scenarios is to test the clipboard feature in an application, this comes in real handy.

Below is a sample illustration :

**********************************************************************

Set cb=CreateObject("Mercury.Clipboard")
' Get the text on the system clipboard.
vText=cb.GetText
msgbox vText

'Clipboard object
Set cb=CreateObject("Mercury.Clipboard")
' Get the text on the system clipboard.
vText=cb.GetText
cb.Clear
Set cb = Nothing

**********************************************************************

** Happy Automating **

QTP-IE-Close All Browsers

One thumb role in testing in general and Automation in specific is get the application to the base state after completion of testing or before starting the test.

With QTP used against web application, there are chances the script fail due to object recognition issues when multiple browser instances are open.
The risk of failure however can be mitigated by using unique properties for each object, but mostly it is advised to close all open instances of browsers if not required for test execution.

Multiple ways of doing it :
Use of IE DOM to close the instances
Use of VBscript to kill all open IE processes
Use of native QTP code to check the window properties and close the browsers

One instance is noted below

*************************************************************************

'Close all open browser opened before QTP launch
'Skip TD/QC if already open
'vTDString : To Skip open TD/QC browsers, pass the window name as parameter

Do while Window("title:=.*Internet.*","index:=0").Exist
vBrowserName = Window("title:=.*Internet.*","index:=0").GetROProperty ("title")
If Instr (vBrowserName, vTDString) Then
Do while Window("title:=.*Internet.*","index:=1").Exist
vBrowserName = Window("title:=.*Internet.*","index:=1").GetROProperty ("title")
If Instr (vBrowserName, vTDString) Then
Exit DO
Else
Reporter.ReportEvent 2, "Closed CT1 Browser", "Closed Browser Session with name '" & vBrowserName & "'"
Window("title:=.*Internet.*","index:=1").Close
End If
Loop
Exit Do
Else
Reporter.ReportEvent 2, "Closed Browser", "Closed Browser Session with name '" & vBrowserName & "'"
Window("title:=.*Internet.*","index:=0").Close
End If

Loop

*************************************************************************

** Happy Automating **

QTP KB 2 - General Error when export/Import Datatable

QTP's famed datatable is third party control similar to excel, many confuse its extension when compared to MS-Excel and implement various formatting features into the excel file, which would be imported during script run.

Since the datatable is not a excel control, there is a high percent chance of corruption, when that happens, the dreaded "General Run Error" is thrown"

Easiest way to workaround is to clear the data in the parent file, and create new one.

Noted below is the HP-Mercury KB article and detailed steps for the same

*************************************************************************
Issue 1: Exporting runtime datasheet to localpath.(Export error no:"-214746725 9")

During runtime, when we try to export the datasheet to local folder we get a general runtime error. So every time we have to kill the QTP and its process tree to proceed.
Solution: Whenever we get ‘General Run Error’ while exporting, clean up the excel sheets as mentioned below and proceed with execution:
How to clean up all Excel formatting from XLS file using QuickTest Professional (QTP)
Making use of the internal logic/functionality offered within QTP, it is possible to clean up Excel format from a XLS file by using either of following methods. By using any of the following methods a new XLS file will result with lower file size once Excel formatting gets removed:
• Using QTP's user interface
1. Open QuickTest Professional and a new blank test script
2. Access the File menu, then select "Settings"
3. Go to the "Resources" tab
4. Under the "Data Table" field, select "Other location" option and click on the browse button ("...")
5. Once the "Open Data Table" dialog appears, find and select the XLS file desired to clean format and click "Open"
6. Click on "Apply" then "Ok" to close dialogs accepting changes Note: depending on the clean up done by QTP, processing time to later show data on the Data Table pane may vary depending on XLS file size and content
7. On the Data Table pane, right click and under "File" option, select "Export..."
8. Select a location/path and name to save this new version of XLS file
• Using VBScript and QTP Automation Object Model (AOM)
Note: The following script is provided for example purposes only. It is not supported by Hewlett Packard.
filepath = "C:\MyExcelFile.xls"

Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set procList = objWMI.ExecQuery("Select * from Win32_Process " & _
"Where Name = 'QTPro.exe' " & _
"Or Name = 'QTAutomationAgent.exe'")
alreadyOpen = false
For Each objProcess in procList
Select Case UCase(objProcess.Name)
Case "QTPRO.EXE"
alreadyOpen = true
Case "QTAUTOMATIONAGENT.EXE"
objProcess.Terminate()
End Select
Next
Set procList = Nothing
Set objWMI = Nothing
On Error Resume Next
Set App = CreateObject("QuickTest.Application")
If Err.Number <> 0 Then
MsgBox "Error Instancing QuickTest.Application class. Assure QTP is installed on machine"
Else
If Not alreadyOpen Then App.Launch
App.New False
App.Test.Settings.Resources.DataTablePath = filepath
Dim aux, filename
aux = Split(filepath, "\")
filename = Split(aux(UBound(aux)), ".")
tempname = filename(UBound(filename)-1) & "_BAK." & filename(UBound(filename))
tempname = Replace(filepath, aux(UBound(aux)), tempname)
App.Test.DataTable.Export tempname
App.Test.Settings.Resources.DataTablePath = ""
Set fso = CreateObject("scripting.filesystemobject")
fso.DeleteFile filepath
fso.MoveFile tempname , filepath
App.New False
If Not alreadyOpen Then App.Quit
End If
Set App = Nothing

**************************************************************************

Any issue with the above code, reach out to HP-Mercury :)

** Happy Automating **

QTP-ChildObjects-1

QTP, being based on Objects, usage of 'Child objects' is an effective feature in identifying a particular object type within a parent object.
Perform actions on the child objects without adding them to the Object Repository.

For instance, if the scenario is to click on all the links on a webpage, and if the link count is more than 100, it is not required to add all the link objects into the repository and click on them.
Instead 'ChildObject' can be used very effectively to retrieve the collection of all links within the page, iterate through the collection and click on each of them as required.

Noted advantages of Childobjects:
Retrieve any object collection
Work on multiple objects without adding them to repository
Suited mainly for UI checks
Suited in cases where the application is dynamic and object properties changes frequently
Minimize the dependency on QTP's object recognition
Lesser maintenance due to elimination of object repository


**************************************************************************

Below is a sample illustration of using childobjects for working with checkboxes in a web application.

**************************************************************************
'Code to count the number of check boxes on a web page

Function getChboxCnt()
'Create current page object
Set iObj = Browser(...).Page(...)
'Create Checkbox description object
Set oDesc = Description.Create()
oDesc("micclass").value = "WebCheckBox"
oDesc("checked").value = 1
Set CC = iObj.ChildObjects(oDesc)
ccc = CC.Count
End Function

******************************************************************

'Code to count the number of check boxes on a web page, within a webtable

Sub chbox_count()
Dim obj_ChkDesc
'Create Checkbox description object
Set obj_ChkDesc=Description.Create()
obj_ChkDesc("html tag").value = "INPUT"
obj_ChkDesc("type").value = "checkbox"

'Create current page object
Set WebPage = Browser(...).Page(...)
Dim allCheckboxes, singleCheckBox
Set allCheckboxes = WebPage.WebTable("name:=allbox","html tag:=TABLE").ChildObjects(obj_ChkDesc)

If allCheckboxes.Count > 0 Then
print "No of check boxes are : "&allCheckboxes.Count
End If
End Sub

******************************************************************


Like the post, encourage you to add your comment
** Happy Automating **

Wednesday, June 2, 2010

MS Outlook COM : Retrieve Recurring Appointment Data

'Script to retrieve recurring item from appointment list
'VBA, would run the script editor along with outlook
'Changes to be done if need to run outside outlook in a vbscript
'Reference : http://msdn.microsoft.com/en-us/library/bb219954.aspx

**************************************************************************

Public Sub Application_GetItem()
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.GetDefaultFolder(9)
Set itms = fld.Items
lngCount = itms.Count
i = 0
For Each itm In itms
If itm.IsRecurring Then
i = i + 1
itm.Display
itm.ClearRecurrencePattern
itm.Close (olDiscard)
End If
Next
End Sub