Monday, January 19, 2015

Test Automation and the Greedy Expectations….!!!

I have been dating Test automation for the past decade and am never bored of it all the time. She has been a fascinating partner, making my life merry when I take care and making it a living hell, when I do not.

Automation is always is a double edged sword and I use this phrase many times today (read decade), because my excitement in automation has led to advocating responsible automation. It’s another question on whether I am able to sell it or not always.

A good part of my energy and effort has gone by in proving Test automation is the right thing for its most hardest critic and Test Automation is not the golden goose for its easiest subscriber.

Automation should not be seen as the magic wand that solves all of the problems, especially Testing. It can address concerns over schedule and cost in the long run, but may fall flat on providing good quality systems if it is being harassed. Automation builds a degree of predictability, but always misses to find out of the box defects.

Test Automation in theory is another piece of code that is built on an existing code called application/system. It would have defects, it would have changes , it would work , it wouldn’t work , it may find defects and it may not find.

Just like the way application code changes very frequently , “AUTOMATION CODE ALSO WOULD CHANGE”. There is no running away from this phenomena.  A lot of times, I have PMs and Architects pointing at failures of Automation. I tell them, it is bound to fail. It should fail. What is the need for it if everything passes ?

I find it hard to understand what they need from Test automation code , is it “Magic”. We plain engineers, architects building line of code dependent on so many facets of software development factors.

If there could be maintenance releases for application code, I ask why couldn’t all accept that automation code base also needs maintenance.

Does anyone believe that Test Automation is more complex than application development, whoa didn’t I raise some eyebrows here.

·         Application code is derived from requirements. Automation code is based on application behavior and requirements.
·         Application code is bound to make the requirements a reality. Automation code should validate the requirements against the built system
·         Application code is usually the first line of representation of requirements, Automation code is built based on multiple representation of requirements (environment, technology, tools, test scenarios etc)

A growing and a relevant trend is to tie automation to the parent code, build components , reduce dependency on UI layers. Absolutely the way to go. Automate as much as possible at the interface layer and as much as needed at the UI layer.

Testing as a function cannot change to build everything at interface layer and abandon the UI layer once for all. The job of test automation is also sign off the system the way end user would do, do we expect the end user to test APIs only ?

The hardest critic of test automation just needs to know the value of test automation, where the hypnotized believer of Test automation wishes for sun.

Today, that’s the unfortunate direction we as an industry are heading at . Everyone wants to automate and everything needs to be automated.

I am fascinated the ease at which “reset button is hit”  , when understanding the expectations from Test automation is desired. We do not learn from mistakes and we always re-invent the wheel. 

Am rest assured, this is not a concern only with Test automation, rather across the board where specializations are involved.

But it is a mystery , on how right things could be overlooked, not because they are not aware but many do not want to be aware. 

Thursday, January 10, 2013

"Test Automator" - An Indentity crisis...

Are we losing our identity . The identity which derived from being a Tester, slowly growing into the fore of Automation.

Being in the industry for close to a decade now, I am worried about that thought of losing our identity.

Automation began as simple record and play back
Moved towards optimization of same process
Framework showed their head
Entry of custom scripting

Now the march is towards writing tools, customizing tools....continue

I am atleast glad, quite a few (whom I interacted in various forum, platforms have their roots from testing), but the newbies today start with Automation. Is this the beginning of the end of Testers ?

'Testers' not from a mundane manual execution standpoint, but the mindset of finding defects, problem cases and above all being an explorator.

Today's we are driven by two terms "Efficiency and Optimization". This has been successful in turning everything in our industry towards a "Code/Package based world".

I wonder, maybe this is how it began, with simple lines of linear code, no testers, lots of defects. Are we heading to a Deja-vu ?...

Let's wait and watch....

As much as being an Automation consultant, I have always cherished the joy of finding defects when compared to thousands of line of code running flawlessly or a home-grown framework etc.

But hey, what’s the fun, if our automation assets don’t discover defects, wouldn’t we be extinct, guess we already are ...!!!

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 **