Thursday

QTP - Associate Object repository at run time in QTP

Methods
Add
Adds an object repository file to the specified position in the collection.
Find
Finds the position of the specified object repository file.
MoveToPos
Moves the object repository file entry from the current position to the specified new position.
Remove
Removes the object repository that is located in the specified position.
RemoveAll
Removes all object repository files from the collection.
SetAsDefault
Sets the object repository files associated with the current action as the default files for all new actions.




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


'Description:


'


'This example opens a test, configures an action's object repositories collection


'and saves the test.


'


'Assumptions:


'There is no unsaved test currently open in QuickTest.


'For more information, see the example for the Test.SaveAs method.


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





Dim qtApp 'As QuickTest.Application ' Declare the Application object variable


Dim qtRepositories 'As QuickTest.ObjectRepositories ' Declare an action's object repositories collection variable


Dim lngPosition





' Open QuickTest


Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object


qtApp.Launch ' Launch QuickTest


qtApp.Visible = True ' Set QuickTest to be visible





' Open a test and get the "Login" action's object repositories collection


qtApp.Open "C:\Tests\Test1", False, False ' Open a test


Set qtRepositories = qtApp.Test.Actions("Login").ObjectRepositories ' Get the object repositories collection object of the "Login" action





' Add MainApp.tsr if it's not already in the collection


If qtRepositories.Find("C:\MainApp.tsr") = -1 Then ' If the repository cannot be found in the collection


qtRepositories.Add "C:\MainApp.tsr", 1 ' Add the repository to the collection


End If





' If InnerWnd.tsr is moved down the list - place it back at position 1


If qtRepositories.Count > 1 And qtRepositories.Item(2) = "C:\InnerWnd.tsr" Then ' If there's more than one object repository and InnerWnd.tsr is in position 2


qtRepositories.MoveToPos 1, 2 ' Switch between the first two object repositories


End If





' If Debug.tsr is in the collection - remove it


lngPosition = qtRepositories.Find("C:\Debug.tsr") ' Try finding the Debug.tsr object repository


If lngPosition <> -1 Then ' If the object repository was found in the collection


qtRepositories.Remove lngPosition ' Remove it


End If





' Set the new object repository configuration as the default for all new actions


qtRepositories.SetAsDefault ' Set object repositories associated with the "Login" action as the default for all new actions





'Save the test and close QuickTest


qtApp.Test.Save ' Save the test


qtApp.Quit ' Quit QuickTest





Set qtRepositories = Nothing ' Release the action's shared repositories collection


Set qtApp = Nothing ' Release the Application object

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


'The following example retrieves an object repository's objects and properties,


'looks for specific test objects using several methods, and copies a test object


'to another object repository.


'********************
'***************************
Dim ImageObj, PageObj, RepositoryFrom, RepositoryTo




Set RepositoryFrom = CreateObject("Mercury.ObjectRepositoryUtil")


Set RepositoryTo = CreateObject("Mercury.ObjectRepositoryUtil")




RepositoryFrom.Load "C:\QuickTest\Tests\Flights.tsr"


RepositoryTo.Load "E:\Temp\Tests\Default.tsr"


Function EnumerateAllChildProperties(Root)


'The following function recursively enumerates all the test objects directly under


'a specified parent object. For each test object, a message box opens containing the


'test object's name, properties, and property values.


Dim TOCollection, TestObject, PropertiesCollection, Property, Msg




Set TOCollection = RepositoryFrom.GetChildren(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine


Set PropertiesCollection = TestObject.GetTOProperties()




For n = 0 To PropertiesCollection.Count - 1


Set Property = PropertiesCollection.Item(n)


Msg = Msg & Property.Name & "-" & Property.Value & vbNewLine


Next


MsgBox Msg




EnumerateAllChildProperties TestObject


Next




End Function




Function EnumerateAllObjectsProperties(Root)


'The following function enumerates all the test objects under a specified object.


'For each test object, a message box opens containing the test object's name,


'properties, and property values.


Dim TOCollection, TestObject, PropertiesCollection, Property, Msg




Set TOCollection = RepositoryFrom.GetAllObjects(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine




Set PropertiesCollection = TestObject.GetTOProperties()


For n = 0 To PropertiesCollection.Count - 1


Set Property = PropertiesCollection.Item(n)


Msg = Property.Name & "-" & Property.Value & vbNewLine


Next




MsgBox Msg


Next




End Function




Function RenameAllImages(Root)


'The following function sets a new name for all image test objects under a specified object.


Dim TOCollection, TestObject, PropertiesCollection, Property




Set TOCollection = RepositoryTo.GetAllObjectsByClass("Image")




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


RepositoryTo.RenameObject (TestObject, "Image " & i)


RepositoryTo.UpdateObject TestObject


Next




End Function




Function RemoveAllLinks(Root)


'The following function recursively enumerates all the test objects under a specified object.


'It looks for all test objects of class Link and removes them from their parent objects.


Dim TOCollection, TestObject, PropertiesCollection, Property




Set TOCollection = RepositoryFrom.GetChildren(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


TOClass = TestObject.GetTOProperty("micclass")




If TOClass = "Link" Then


RepositoryFrom.RemoveObject Root, TestObject


End If




EnumerateAllChildProperties TestObject


Next




End Function

Monday

QTP/QC - Schedule the testset in QC by VBS

'User must Admin at the machine where he want to run the testset
'This can run manual as well as Automated test suite
' It can be schedule at any partcular future time
' User need not to open the QC

Public Sub RunTestSet(otdc,tsFolderName,tSetName,HostName,runWhere)


Dim TSetFact, tsList
Dim theTestSet
Dim tsTreeMgr
Dim tsFolder
Dim Scheduler
Dim nPath
Dim execStatus
' Get the test set tree manager from the test set factory
'tdc is the global TDConnection object.
Set TSetFact = otdc.TestSetFactory


Set tsTreeMgr = otdc.TestSetTreeManager


' Get the test set folder passed as an argument to the example code


nPath = "Root\" & Trim(tsFolderName)


Set tsFolder = tsTreeMgr.NodeByPath(nPath)


If tsFolder Is Nothing Then


err.Raise vbObjectError + 1, "RunTestSet", "Could not find folder " & nPath


End If



' Search for the test set passed as an argument to the example code



Set tsList = tsFolder.FindTestSets(tSetName)



If tsList Is Nothing Then


err.Raise vbObjectError + 1, "RunTestSet", "Could not find test set in the " & nPath


End If



If tsList.Count > 1 Then


MsgBox "FindTestSets found more than one test set: refine search"


Exit Sub


ElseIf tsList.Count < 1 Then

MsgBox "FindTestSets: test set not found"


Exit Sub


End If


Set theTestSet = tsList.Item(1)


Debug.Print theTestSet.ID


'Start the scheduler on the local machine


Set Scheduler = theTestSet.StartExecution(HostName)



'msgbox "pass"


'Set up for the run depending on where the test instances


' are to execute.




Select Case runWhere


Case "RUN_LOCAL"


'Run all tests on the local machine


Scheduler.RunAllLocally = True


Case "RUN_REMOTE"



'Set Scheduler = theTestSet.StartExecution(HostName)


'Run tests on a specified remote machine


Scheduler.TdHostName = HostName


'Scheduler.TdHostName=runWhere


' RunAllLocally must not be set for


' remote invocation of tests.


' Do not do this:


' Scheduler.RunAllLocally = False


Case "RUN_PLANNED_HOST"


'Run on the hosts as planned in the test set


Dim TSTestFact, TestList


Dim tsFilter


Dim TSTst


'Get the test instances from the test set


Set TSTestFact = theTestSet.TSTestFactory


Set tsFilter = TSTestFact.Filter


tsFilter.Filter("TC_CYCLE_ID") = theTestSet.ID


Set TestList = TSTestFact.NewList(tsFilter.Text)


Scheduler.RunAllLocally = False


End Select



'Run the tests


Scheduler.run



Set execStatus = Scheduler.ExecutionStatus



While (RunFinished = False)


execStatus.RefreshExecStatusInfo "all", True


RunFinished = execStatus.Finished


Wend


End Sub




'================================




Const qcHostName = "GiveQChost:8080"


Const qcDomain = "GiveDomain name"


Const qcProject = "GiveProject" 'Please define here the name of the project


Const qcUser = "User ID" 'Please define here the username



Const qcPassword = "Give Password HGBGH%3&42" 'Please define here the password


Dim tdc


Dim qcServer


Dim objArgs


Dim strArg


Dim strTestSet


Dim bRunCode



'======GETTING ARGUMENTS==============


set objArgs = WScript.Arguments


If WScript.Arguments.Count<1>2 Then


WScript.Echo "Remote_Scheduler"


bRunCode = False


Else


For Each strArg in objArgs


WScript.Echo strArg&" is starting…"


strTestSet = strArg


bRunCode = True


Next


End If


'===========================================================




If bRunCode Then


qcServer = "http://" & qcHostName


qcServer = qcServer & "/qcbin"


Set tdc = CreateObject("tdapiole80.tdconnection")




If (tdc Is Nothing) Then


MsgBox "tdc object is empty"


End If


tdc.InitConnectionEx qcServer


tdc.Login qcUser, qcPassword


tdc.Connect qcDomain, qcProject




RunTestSet tdc, "GiveFolder Name of Test Set","GiveTestSet name ","Givemachinename", "RUN_REMOTE"


'Disconnect from the project


If tdc.Connected Then


tdc.Disconnect


End If


'Log off the server


If tdc.LoggedIn Then


tdc.Logout


End If


'Release the TDConnection object.


tdc.ReleaseConnection


'"Check status (For illustrative purposes.)


Set tdc = Nothing


End IF

Friday

QTP - Thing to know , things of practical learning, small things but worth to spent time with

This post will update whenever I will find anything new/Intresting or just to remember or to know (n FAQ) :

Q1. what is OTA API in QC
The Open Test Architecture API is a COM library that enables you to:
nintegrate external applications with Quality Center
ninteract with the Quality Center application without having to use the GUI front-end
ninteract with the QC databases bypassing DBA

More Info: connectedtesting.com/Presentations/QC%20OTA%20presentation.ppt

QTP/QC - Running bat file from QC

Povide the bat file 'Driverbat.bat' remove ' sign and put bat under folder C:\QTP_Resource.
'cd C:\QTP_Resource
'DriverScript_QTP
'C:\QTP_Resource\Utility2.exe auto some other utility
'Exit

In QC > Create a VAPI-XP test > in test script put the code

Dim objShell


Set objShell = CreateObject("WScript.Shell")


'objShell.Run "CMD.exe"



objShell .Run "%comspec% /k c: & cd C:\QTP_Resource Driverbat.bat"
BR>
'objShell.Run "%comspec% /k c: & cd C:\QTP_Resource\\Driverbat.bat"
BR>
'qtAppWin.sendkeys "~"

QTP - Creating a XML file (Output.xml) by FileSystemObject

Call createLog


Call OpenBrowser


Call TestCase1


Call TestCase2


Call TestCase3


Call CloseLog


Function CreateLog()


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile = TRFSO.CreateTextFile(TRFileName)


MyTRFile.WriteLine("")


MyTRFile.WriteLine("")


MyTRFile.close


Set TRFSO=Nothing


End Function




Function CloseLog()


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile=TRFSO.OpenTextFile(TRFileName,8,True)


MyTRFile.WriteLine("
")


MyTRFile.close


Set TRFSO=Nothing


End Function




Function WriteLog(Msg)


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile=TRFSO.OpenTextFile(TRFileName,8,True)


MyTRFile.WriteLine(Msg)


MyTRFile.close


Set TRFSO=Nothing


End Function




Function OpenBrowser()


SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE"


'Rerecord SystemUtil step


Browser("X").Page("Y").Sync


Browser("X").Page("Y").Sync.Navigate "http://www.Someapp.com"


End Function




Function TestCase1()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


End If


End Function




Function TestCase2()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


End If


End Function




Function TestCase3()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


wait(2)


if Browser("X").Exist Then


Browser("X").close


End If


End If


End Function

Tuesday

QTP- Execute the bat file , dos command from QTP

dim appset app=createobject("wscript.shell")
SystemUtil.run "cmd.exe"
app.sendkeys "cd C:\Documents and Settings\'<>\"
app.sendkeys "~"
app.sendkeys "MyDosFile.bat"
app.sendkeys "~" app.sendkeys "~"
wait(5)

'In bat file you can give and save
Date
echo "hello World"
pause

Monday

QTP - Blocking/Unblocking the pop-Up by QTP

Sometime the Pop-ups create problem while running the script (Browser pop-ups). To overcome this problem we can manipulate Registry key.
QTP can use this function.

'Create the shell object
Set WshShell = CreateObject("WScript.Shell")

'Path to edit in registry
popupKeyPath = "HKCU\Software\Microsoft\Internet Explorer\New Windows\PopupMgr"

'Disable the IE pop-up blocker
WshShell.RegWrite popupKeyPath, "no", "REG_SZ”

‘Enable the IE pop-up blocker
WshShell.RegWrite popupKeyPath, "yes", "REG_SZ”

QTP - VBSscript to start server

'This VBSscript to start server 'To start servers on Windows/Unix/Linux server
Dim w3sock Set w3sock = CreateObject("socket.tcp")
With w3sock
.timeout = 6000
.DoTelnetEmulation = True
.TelnetEmulation = "TTY"
.Host = "localhost:2023"
.Open
.WaitFor "login:"
WScript.Echo .Buffer
.SendLine "Provide your User ID"
.WaitFor "password:"
.SendLine "Provide your Password"
.WaitFor ">"
.SendLine "net start ""Server Mgr"""
.WaitFor ">"
WScript.Echo .Buffer
.Close
End With
Set w3sock = Nothing
'Install w3socket somewhere like dimac.net/

QTP - Comparison between SilkTest and QTP


FeatureQTPSilkTest
Record and Play Supported Supported
Scripting Language VBScript 4test, Similar to C++
Object recognition based on Object properties, DOM structure based on Object properties, DOM structure
Browser Support IE & FF are supported IE & FF are supported
QC Integration Possible Found a doc, but not validated yet.
CA License Yes Yes; But, only one we believe
Learning Curve Less effort Considerable effort required
Integration with external libraries Possible NO
Tech Support Yes Yes
Current Release v10.0 v9.2.1
Test Project/TestPlan (Test Orgnization) Not Avilable Avialble
Exception Handling by Tool Excellent Moderate
Virtual Object Concept for Custome Object Avilable
DLL support Both COM and Standard DLLs are supported. Only Standard DLLs. It does not support the COM/ActiveX DLLs, which are created by VB/.NET.
Distributed Testing Remote Agent COM Agent. Remote Agent.
Results Reporting QTP results are stroed as XML files and can be converted to HTML files. Result folder contain many files. One result folder can store results for only one run. Results are stored into *.res binary files. It can be converted into differnt formats. Multiple versions can be stored into single file.
Verification Provided check points for different purposes. Provided Verify and Verify Properties functions.
OOPs Support Not supported Oops concepts are supported for certain extent. User can extend standard classes.
Active Screen Kind Feature to modify test better even when App is down. Avilable - Keyword View, Expert View Not Avilable - Classic 4Test, Visual 4Test
Objects Repository Maintained as separate file. With the help of utility, objects are modified. Two types as per QTP setting. They are 'Per Action Repository' and 'Shared Repository'. File extensions will be varied for each type. Official term is Window declarations. They can be edited directly from the Editor
Custom Classes Virutal Object Wizards available. RecorderClass and Extension Kit are available.
Environment support Can access OS level variables. Can access OS level variables.
Internatioalization (i18N) Support YES YES
Java/>NET/Flex Support YES YES
OS Windows upto Vista Windows upto Vista, Unix (SilkBean)
Data functions DataSheet ( Local and Global) Extensive feature Fair
Documentation Both CHM and PDF files are available. Enough info. HLP file available. PDF docs are only for beginners.
Associated Utilites Provide lots of Utility like batchrunner,OR merge tool, Silent Runner, PasswordEncoder,Remote Agent, Movie Recorder, SilentRunner Less Utilites though Extension kit is there.
Product Name Changes Initially Astra QuickTest. Later changed to HP QuickTest Professional. Initially QA Partner. Later changed to Borland SilkTest
Vendor HP (Hewlett-Packard). Initially developed by Mercury Interactive. HP acquired Mercury on 2006. Microfocus. In past Borland. Initially developed by Segue. Borland acquired Segue on 2006.
Strengths The most popular test tool by great user base, plenty of jobs, good online community, Good cross browser support Good Development language, good online community, recovery system, Good cross browser support, Code Maintenance
Editor Better one with nice look. But using tabs to show more than one script. Good. Simple one. Having Project explorer similar to MS Visual Studio.
Ease of use Record and playback used to help. Very Simple. Easy to learn. Just record and playback, won't help. Medium.
Data types Set of data types are available. User cannot create their own data types Set of data types are available. User can create their own data types also.
Code Samples Few samples from vendor. But many VB Script samples available on Internet. Few samples from vendor.
Batch Run Test Batch Runner utility. Suite (*.s) and Test plan (*.pln) are available.
Test Management Tool Integration Integrated with Quality Center. Integrated with SilkCentral Test Manager.
Dynamic objects Object properties can be passed dynamically. Another term is known as Descriptive Programming. Object properties can be passed dynamically. Variety of methods available to handle them.
Objects Repository Maintained as separate file. With the help of utility, objects are modified. Two types as per QTP setting. They are 'Per Action Repository' and 'Shared Repository'. File extensions will be varied for each type. Official term is Window declarations. They can be edited directly from the Editor.
Test Script Actually Script is a folder and have set of supporting files. Script is a single file.
Tests Termed as Actions. Each Action has block of coding statements. Termed as Testcase. Each Testcase has block of coding statements.
Database tests With the help of DSN (ODBC32 Interface) plus VB Scripting With the help of DSN (ODBC32 Interface)
Browsers support Internet Explorer, Netscape, FireFox, AOL Internet Explorer, Netscape, FireFox, AOL


Comon Object Identification Issues (including label changes) and how QTP and Silk approach to resolve that. The Object Identification Cases and resolution:
1. Name/label Change

QTP: Only need to Modify property/properties in OR. It will reflect the same in all scripts.

SilkTest: Modifying the Window tag will solve the purpose.Conclusion: Logically both are doing same thing. The appearance and organization of keeping Object property is different.We need to keep the logical and physical name separate for both.
2. A DialogBox that can have different parents

QTP: QTP physically Store the hierarchy, so there will not be any issue. We can use DP ( descriptive programming) to handle this scenario.

SilkTest: Using windowtag, tag “..\{Object-name}” can associate any object to any parentConclusion: QTP might take DP effort if hierarchy changes very frequently . On the other hand Silk can associate parent on the fly.
3. A Browser Child with a non-unique tag

QTP: Creation Time and separate hierarchy in OR makes things easier

SilkTest: BrowserChild indexing solve problem but have restriction.Conclusion: QTP having better mechanism for it.
4. A window tag that contains variable characters

QTP: Regular expression, DP, Get/Set properties are the example to resolve this kind of issue

SilkTest: Using wildcard characters/Reg Exp can solve the issueConclusion: QTP provide multiple ways to handle it as mentioned above.
5. An object whose index varies based on application context

QTP: Indexing at the level of OR, We can use it in Code also but not very encouraging

SilkTest: It use index property with variety.Conclusion: Silk use programming approach and it support indexing property in great detail.
6. An object where one or more instance may exists

QTP: Exist, Wait, WaitProperty, OST,Timeout are the way to find that Object exist or not. Can be write simple logic for timeout also.

SilkTest: Sleep, Exist function available. Can be write simple logic for timeout also.Conclusion: Logically both are doing same thing.
7. Non-Unique Properties

QTP: Smart Identification, Ordinal Identifier

Silktest: MultiTagingConclusion: Logically both are doing same thing. It is not recommended to enable theses option for robust automation.

Sunday

QTP - Terminate process , Close all browser

'************************************************' Killing the process By QTP'************************************************Killprocess ="EXCEL.EXE"Killprocess2 = "calc.exe"Killprocess3 = "mspaint.exe"Set ProcessList = GetObject("winmgmts://.").InstancesOf("win32_process")For Each Process In ProcessList If Process.Name = KillProcess Then Process.Terminate End IfIf Process.Name = KillProcess2 Then Process.Terminate End ifIf Process.Name = KillProcess3 Then Process.Terminate End ifNext
'************************************************'Closing all the Browser Locally'************************************************KillprocessIE ="IEXPLORE.EXE"Set ProcessList2 = GetObject("winmgmts://.").InstancesOf("win32_process")
For Each Process In ProcessList2 If Process.Name = KillProcessIE Then Process.Terminate End IfNext
While Browser("CreationTime:=0").Exist Browser("CreationTime:=0").CloseWend
'************************************************'Closing all the Browser by WBI Object remotely'************************************************'Alternatively WMI (Window management instrumentation ) object can be Used'sComp is IP of the remote machine
SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"sComp="shukr02-xp"Set WMIobj = GetObject("winmgmts:\\" & sComp & "\root\cimv2") ' Find All the iexplore.exe processes Set IEExp = WMIobj.ExecQuery("Select * from Win32_Process Where Name = 'IEXPLORE.EXE'")
For Each IEx in IEExp IEx.Terminate()Next'************************************************'SystemUtil Object'************************************************SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"NumberOfProcess = SystemUtil.CloseProcessByName("iexplore.exe")
'Check If Browser Exist and if the close it'SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"While Browser("creationtime:=0").Exist(0) Browser("creationtime:=0").CloseWend'**********************************************

QTP Tip1: The first browser that opens receives the value "CreationTime" = 0, the second browser receives "CreationTime" = 1, and so on...QTP Tip2: To specify value of property in Descriptive Programming, please use ":=" operator.For example, "Title:=My application".Since we cannot know in advance - what browser will be selected and closed, we use its "age", i.e. "CreationTime" property. We decide, which browser should be closed, during the QTP script execution only.Let's return to above QTP script...
Browser("CreationTime:=0").Exist - it checks whether the first opened browser exists or not
If the browser exists, we close it - Browser("CreationTime:=0").Close - and repeat checkingLet's continue сomplicating our task:
How to close browsers by mask?For example, we have to close all browsers navigated to any Google's sites (URL contains 'google.com').In this case, QTP script will look like:
(Click the image to enlarge it)Using this QTP code, you can close dynamically browsers by mask.Please, note several useful QTP tips.QTP Tip3: To get browser's URL, use: GetROProperty("URL") function.For example, this line returns URL of the first opened browser:
Browser("CreationTime:=" & CreationTime).GetROProperty("URL")QTP Tip2: Analogously, to get browser's Title, use: GetROProperty("Title") function.
Browser("CreationTime:=" & CreationTime).GetROProperty("Title")

Thursday

Dictionary Object in QTP

Dictionary Object
Dictionary Object stores data key, item pairs. A Dictionary object stores the items in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

Adavntages of using it in QTP:
1. can be used as Global variable declaration. so that any test can access the values from it in the run time.
2. You can store and retrive any number of run time values in to dictonary.
3. It is one of the Parameterization techique we can use in QTP

Disadvantages:
we can not specify the values in the desingn time like Datatable , Action parameters, environment variable.
So it is useful only in Run time , not design time
Methods:
Add Method
Adds a key and item pair to a Dictionary
object. object.Add (key, item)
Arguments
object Required. Always the name of a Dictionary object.
key Required. The key associated with the item being added.item Required.
The item associated with the key being added.
Remarks
An error occurs if the key already exists.
The following example illustrates the use of the Add method.
Dim d ‘ Create a variable.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”

Items Method
Returns an array containing all the items in a Dictionary object.
object.Items( )
Remarks The object is always the name of a Dictionary object.The following code illustrates use of the Items method:
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
a = d.Items ‘ Get the items.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & “
” ‘ Create return string.
Next
Msgbox s
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
object.Exists(key)
Arguments
object Required. Always the name of a Dictionary object.
key Required. Key value being searched for in the Dictionary object.
Remarks
The following example illustrates the use of the Exists method.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
If d.Exists(”c”) Then
Msgbox “Specified key exists.”
Else
Msgbox “Specified key doesn’t exist.”
End If
Keys Method
Returns an array containing all existing keys in a Dictionary object.
object.Keys( )
Remarks
The object is always the name of a Dictionary object.
The following code illustrates use of the Keys method:
Dim a, d, i ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
a = d.Keys ‘ Get the keys.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & “
” ‘ Return results.
Next
Msgbox s
Remove Method
Removes a key, item pair from a Dictionary object.
object.Remove(key)
Arguments
object Required. Always the name of a Dictionary object.
key Required. Key associated with the key, item pair you want to remove from the Dictionary object.
Remarks
An error occurs if the specified key, item pair does not exist.
The following code illustrates use of the Remove method:
Dim a, d ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo” …
d.Remove(”b”) ‘ Remove second pair.
RemoveAll Method
The RemoveAll method removes all key, item pairs from a Dictionary object.
object.RemoveAll( )
Dim a, d, i ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo” …
a = d.RemoveAll ‘ Clear the dictionary.

Example :
'Defining The Dictionary ObjectDim dict Set dict = CreateObject("Scripting.Dictionary")
'Add Methoddict.Add "Company", "Indian Railway" ' Adding keys and corresponding items.dict.Add "Tool", "QuickTest Pro"dict.Add "Website", "QTPDictionary"dict.Add "Country", "India" x= dict.CountmsgBox "Total Number of Object in dictionary:: " & x
'Exist MethodIf dict.Exists("Country") Thenmsg = "This is India."msgBox msgElsemsg = "India is not in a country list."End If
'Item Methodi = dict.Itemsk = dict.KeysFor x = 0 To dict.Count-1 'Iterate the array.msgbox i(x) & " :" & k(x)Next
'Remove dict.Remove("Website")
'Remove All
dict.RemoveAll

Wednesday

SendKey and QTP - Sending Keyboard Command

Please find the three ways to send the keyboard command to application.

Please find the script below and just run in QTP. It will invoke Notepad. It will put the time stamp, find the string in the text by these function.


'**********************************************************************************
''Start The Type/Send Key / Device Reply
'*********************************************************************************
' Open Notepad
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""

'**********************************************************************************
'Type Method Sending to Application
'**********************************************************************************
Window("Notepad").WinEditor("Edit").Type "This is Type Method Example"
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We Will enter the Current Date from Menu > Edit > F5 Keyboard, The Date will come in Next line below:::"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(1)
Window("Notepad").WinEditor("Edit").Type micF5

wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click

'**********************************************************************************
''SendKey Methoid to Application
'**********************************************************************************
wait(2)
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""
Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate("Untitled - Notepad")
WshShell.AppActivate "Notepad" ' Activate the browser window
Window("Notepad").WinEditor("Edit").Type "This is SendKey Example "
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We are finding the word Opened by upword Searching and then cancling the findings"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(3)
WshShell.SendKeys "^f"


wait(1)
Window("Notepad_2").Dialog("Find").WinRadioButton("Up").Set
Window("Notepad_2").Dialog("Find").WinEdit("Find what:").Set "opened"
Window("Notepad_2").Dialog("Find").WinButton("Find Next").Click
Wait(2)
Window("Notepad_2").Dialog("Find").WinButton("Cancel").Click
wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click

'**********************************************************************************
'Device Reply Method to application using DeviceReplay.
'**********************************************************************************

Set obj = CreateObject("Mercury.DeviceReplay")
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""
Window("Notepad").Activate

Window("Notepad").WinEditor("Edit").Type "This is Device Reply Example"
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We Will enter the Current Date from F5 hot Key, The Date will come in Next line below:::"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(1)
obj.PressKey 63 '63 is the ASCII value for F5
Wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click
'ASCII values for other keys: F1 - 59 F2 - 60 F3 - 61 F4 - 62 F5 - 63 F6 - 64 F7 - 65 F8 - 66 F9 - 67 F10 - 68 F11 - 87 F12 - 88
‘ For More Value see the http://www.lookuptables.com/
'**********************************************************************************
'End The Type/Send Key / Device Reply
'**********************************************************************************

You can use SendKeys to send more than one keystroke at a time. To do this, create a compound string argument that represents a sequence of keystrokes by appending each keystroke in the sequence to the one before it. For example, to send the keystrokes a, b, and c, you would send the string argument “abc”. The SendKeys method uses some characters as modifiers of characters (instead of using their face-values). This set of special characters consists of parentheses, brackets, braces, and the:
plus sign ”+”,
caret ”^”,
percent sign “%”,
and tilde ”~”
Send these characters by enclosing them within braces “{}”. For example, to send the plus sign, send the string argument “{+}”. Brackets “[ ]” have no special meaning when used with SendKeys, but you must enclose them within braces to accommodate applications that do give them a special meaning (for dynamic data exchange (DDE) for example).
To send bracket characters, send the string argument “{[}" for the left bracket and "{]}” for the right one.
To send brace characters, send the string argument “{{}” for the left brace and “{}}” for the right one.
Some keystrokes do not generate characters (such as ENTER and TAB). Some keystrokes represent actions (such as BACKSPACE and BREAK). To send these kinds of keystrokes, send the arguments shown in the following table:
Key
Argument
BACKSPACE
{BACKSPACE}, {BS}, or {BKSP}
BREAK
{BREAK}
CAPS LOCK
{CAPSLOCK}
DEL or DELETE
{DELETE} or {DEL}
DOWN ARROW
{DOWN}
END
{END}
ENTER
{ENTER} or ~
ESC
{ESC}
HELP
{HELP}
HOME
{HOME}
INS or INSERT
{INSERT} or {INS}
LEFT ARROW
{LEFT}
NUM LOCK
{NUMLOCK}
PAGE DOWN
{PGDN}
PAGE UP
{PGUP}
PRINT SCREEN
{PRTSC}
RIGHT ARROW
{RIGHT}
SCROLL LOCK
{SCROLLLOCK}
TAB
{TAB}
UP ARROW
{UP}
F1
{F1}
F2
{F2}
F3
{F3}
F4
{F4}
F5
{F5}
F6
{F6}
F7
{F7}
F8
{F8}
F9
{F9}
F10
{F10}
F11
{F11}
F12
{F12}
F13
{F13}
F14
{F14}
F15
{F15}
F16
{F16}
To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT, CTRL, or ALT, create a compound string argument that represents the keystroke combination. You do this by preceding the regular keystroke with one or more of the following special characters:
Key
Special Character
SHIFT
+
CTRL
^
ALT
%
Note When used this way, these special characters are not enclosed within a set of braces.
To specify that a combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to send the keystroke combination that specifies that the SHIFT key is held down while:
e and c are pressed, send the string argument “+(ec)”.
e is pressed, followed by a lone c (with no SHIFT), send the string argument “+ec”.
You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed several times in a row. To do this, create a compound string argument that specifies the keystroke you want to repeat, followed by the number of times you want it repeated. You do this using a compound string argument of the form {keystroke number}. For example, to send the letter “x” ten times, you would send the string argument “{x 10}”. Be sure to include a space between keystroke and number.
Note The only keystroke pattern you can send is the kind that is comprised of a single keystroke pressed several times. For example, you can send “x” ten times, but you cannot do the same for “Ctrl+x”.
Note You cannot send the PRINT SCREEN key {PRTSC} to an application.