Synchronizing Script Execution between different machines
The following code shows how to get the environment of a local or a remote PC using AOM
'Get an object reference to the running QTP Set qtpLocalPC = CreateObject("QuickTest.Application") sRemoteIP = "10.1.1.1" Set qtpRemotePC = CreateObject("QuickTest.Application", sRemoteIP)
'Then get its Environment object Set qtpLocalEnv = qtpLocalPC.Test.Environment Set qtpRemoteEnv = qtpRemotePC.Test.Environment
'Lastly, access the environment variables MsgBox qtpLocalEnv("TestDir") MsgBox qtpRemoteEnv("TestDir") |
We want to wait for QTP to reach a point,we have the script update the environment variable after reach that point
'Create a SyncPoint environment variable here Environment.Value("SyncPoint1") = False
Msgbox "Job 1 Completed" 'Do some operations '<-- Another job waiting for execution to reach this point Environment.Value("SyncPoint1") = True
Msgbox "Starting Job 2" |
This Script wait for QTP to reach the point(SyncPoint1) to start its execution
'Script 2 'Local machine IP strCompIP = "127.0.0.1"
Set qtpApp = CreateObject("QuickTest.Application", strCompIP)
'Wait till the script has not started While Not qtpApp.Test.IsRunning Wend
'Now wait for the SyncPoint environment variable to be true While qtpApp.Test.Environment("SyncPoint1") <> True Wend
MsgBox "Script 1 has passed the sync point." |
Enumerating the Setting Variables
Method1 l-looking for settings in Registry
First launch regedit.exe from the window Run Dialog,there are two main keys where the settings variable exists
HKEY_LOCAL_MACHINE\SOFTWARE\MERCURY Interactive\QuickTest Professional\MicTest\
HKEY_LOCAL_MACHINE\SOFTWARE\MERCURY Interactive\QuickTest Professional\PacKages\
We can access the supported data inside the TSRManager key,we need to use the following code
msgbox setting("TSRManager")("Supported") |
Note:changing some of these setting at run-time might cause unexpected behavior
Method2
Enumerating
the Setting Objects and Variables
The Setting Object is actually the
“mercury.Scriptings”COM
library,this library provide two undocumented arrarys for Enumerating,the arrays named keys and items(return all the object/values stored for given index/key)
'ObjSetting is of Type Public Function EnumerateSettings(objSetting) 'Get arrays of key vKeys = objSetting.Keys
'Get the 2nd dimenstion of the Keys array i_Count = UBound(vKeys,2)
' On error resume next
'Loop through all the keys and get the details For i = 0 to i_Count DataTable("Key",dtGlobalSheet) = vKeys(0,i) DataTable("Value",dtGlobalSheet) = objSetting.Item(vKeys(0,i)) DataTable("Type",dtGlobalSheet) = TypeName(objSetting.Item(vKeys(0,i))) DataTable.GlobalSheet.SetCurrentRow i+2 Next End Function Call EnumerateSettings(Setting) |
We can get a list from the datatable:
Key |
Value |
Type |
(default) |
|
String |
actionsspath |
C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\advance\Action1 |
String |
activepanetab |
0 |
Long |
addin manager |
|
IScriptSetting2 |
additionalfunclibfileslist |
|
String |
advancedlockmode |
0 |
String |
allowtdconnect |
1 |
Long |
analogreplay |
0 |
Long |
appendresfiles |
False |
Boolean |
appfunclibfileslist |
|
String |
applicationtypename |
QuickTest Professional |
String |
|
IScriptSetting2 | |
autmode |
0 |
Long |
automaticlinkcheck |
0 |
Long |
automaticlinkrun |
0 |
Long |
autotmprunmode |
-1 |
Long |
browserinvokingsettled |
0 |
Long |
browserstepcount |
695 |
Long |
browsertype |
IE |
String |
businesscomponentiter |
0 |
Long |
checkbrokenlinks |
0 |
Long |
checkforupdates |
1 |
Long |
checkhtmlcontent |
0 |
Long |
checkhtmltag |
0 |
Long |
checkimagessource |
1 |
Long |
checklinksurl |
1 |
Long |
checkloadtime |
1 |
Long |
checknumberofimages |
1 |
Long |
checknumberoflinks |
1 |
Long |
closebrowser |
0 |
Long |
connectscriptdebuger |
1 |
Long |
copyresinsaveas |
False |
Boolean |
copysnapinsaveas |
True |
Boolean |
currentreportpath |
C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\advance\Res10 |
String |
datatablepath |
|
String |
debuginitfailure |
0 |
Long |
defaultdelay |
500 |
Long |
defaultloadtime |
10 |
|
If we notice the type of the various keys we will notice that many of them have “IScriptSetting2” which is nothing but the Interface for “mercury.Scriptings”,it means we can also enumerate that object using the same method we used for the Setting object,for example
Call EnumerateSettings(Setting("attributes")) |
The table below Shows some of the settings and the description for them
Setting("FirstGlobalIteration") |
Starting iternation row number of the global data table from the run Settings |
Setting("LastGlobalIteration") |
Ending iternation row number of the global data table from the run Settings |
Setting("GlobalIterationMode") |
The Iteration mode in the run setting 1=Run on all rows 2=Run on single row/Run on specified rows |
Setting("DisableRepalyUsingAlgorithm") |
Disable smart identification at run-time 0= smart identification enabled 1= smart identification disabled
|
Setting("OnPlayError") |
Set what action need to be taken in case an error occurs while replaying the script Following are the possible values Dialog=Pop up message box nextIteration=proceed to the next action stop=stop run skip=proceed to the next step |
Setting("UseExternalDatatablePath") |
Whether a external data table is being used or not 0=No external dataTable 1=External dataTable |
Setting("ExternalDataPath") |
Path of external datatable in case UseExternalDatatablePath is 1 |
Setting("SnapshotOnErrorActiveUI") |
Save image to deskstop when error occurs 0=disabled 1=enabled |
setting("TSRManager")("ObjRepType") |
Type of the Repository being used in the test 0=Per-action repository 1=shared object Repository |
setting("TSRManager")("TSRFilePath") |
File Path of the shared object repository in case ObjRepType=1 |
setting("TSRManager")("DefaultObjRepType") |
Default Type of the Repository being used in the test 0=Per-action repository 1=shared object Repository |
Setting("RepalyRecovery")(“enabled”) |
Recovery scenarios 0=disabled 1=enabled |
Setting("isreadyOnly") |
The script opened in the read only type True -Read-Only False-read/write |
Setting("actionsPath") |
CurrentActionsPath on the local machine |
Setting("launchreport") |
View test result after run is completed 0-Do not show any results 1- show the results |
Setting persistence
在运行时添加这些Setting变量在脚本完成时不会销毁,除非QTP关闭或者一个新的脚本打开
The following code demonstrates this persistence
If Setting.Exists("Session") Then msgbox "The Session exists" else Setting.Add "Session","Session1" msgbox "Session created" End If
|
The first run displays the message "session created" while the subsequent runs of the same QTP run display "The Session exists",this demonstrate the Settings are persisted in memory
Stop and Re-Run QTP Using Code(没太看懂)
有如下的几种情况需要重新启动QTP
1、 场景恢复在运行时添加,他不能应用于test,除非停止并且重新运行
2、
'Function stop and restart QTP Sub StopAndReRunQTP(restartFlag) 'Only restart if the flag has not been used If Setting.Exists(restartFlag) = False then 'Flag does not exist add. Settings added at 'run-time are kept for whole session of QTP Setting.Add restartFlag,True 'Call the routine for launching jon to 're-run QTP after we have stopped QTP Call AsyncReRunQTP
'Disable reporting failure Reporter.Filter = rfDisableAll
'Change the setting to stop on any error Setting("OnReplayError") = "Stop"
'Stopping Test by causing an intentional error Err.Raise vbObjectError + 1,"Stop", "Causing Error for Stopping QTP" End if End Sub
Sub AsyncReRunQTP() 'Create the re-run script at run-time Call CreateQTPRunScript()
'Run the script asynchronously Set wShell = CreateObject("WScript.Shell") wShell.Run "ReRunQTP.vbs" End Sub
Public Function CreateQTPRunScript() 'Create script to wait for QTP to stop and then re run it Set fso = CreateObject("Scripting.FileSystemObject") set file = fso.OpenTextFile("ReRunQTP.vbs",2, True) file.WriteLine "Set qtpApp = CreateObject(""QuickTest.Application"")" file.WriteLine "While qtpApp.Test.IsRunning" file.WriteLine "Wend" file.WriteLine "qtpApp.Test.Run ,False" file.close set file = nothing set fso = nothing End Function |
Adding Recovery Scenarios at run time
Recovery scenariocan be added at run-time using AOM,but we need to stop and re-run function as described above
'Check if the setting exists or not If Not Setting.Exists("AddingRecoveryScenario") then Dim qtpApp 'Add the recovery scenario Set qtpApp = CreateObject("QuickTest.Application") qtpApp.Test.Settings.Recovery.RemoveAll qtpApp.Test.Settings.Recovery.SetActivationMode "OnEveryStep" sRecoveryFileName = "C:\Program Files\Mercury Interactive\" _ & "QuickTest Professional\recovery\WebRecovery.qrs" qtpApp.Test.Settings.Recovery.Add sRecoveryFileName, "Security Warning", 1 qtpApp.Test.Settings.Recovery.Item(1).Enabled = "True" StopAndReRunQTP "AddingRecoveryScenario" End If |
Executing code when Script ends
VBScript don’t have script start or script end evens, execute some code at the start of a script is easy which is done by adding that code in the vbs file and associating it with the test resource.
We can execute a code at end of script to export a datatable , this is commonly done at the end of the last action ,but the problem is when we are using global iteration, the code will called again and again ,we can give a workaround to execute the code at the last iteration only:
If environment.value("testIteration")=setting("LastGlobalIteration") then dataTable.export "C:\Test.xls" End if |
The code above works fine in most situations but when it fails when we have imported the global sheet as setting("LastGlobalIteration") is not updated at run time.
A solution to this problem:
'place this code into the C:\LoadUnload.vbs file Class LoadUnload Sub Class_Initialize() MsgBox "Initialized" End Sub
Sub Class_Terminate() MsgBox "Terminated" End Sub End Class
Dim oLoadUnload Set oLoadUnload = New LoadUnload |
the following example provide a solution that works with both QTP8.X and 9.X
'Variable declaration Dim FSO Dim xlApp Dim oMyClass
Class MyClass '.... End Class
Class LoadUnload Sub Class_Initialize() Set FSO = CreateObject("Scripting.FileSystemObject") Set xlApp = CreateObject("Excel.Application")
Set oMyClass = New MyClass End Sub
Sub Class_Terminate() On Error Resume Next 'Clean up all the objects Set FSO = Nothing
'Close all open sheet and quit excel For Each workBook In xlApp.Workbooks 'Close the work book and dont save changes workBook.Close False Next
'Quit the Excel application xlApp.Quit
Set xlApp = Nothing
Set oMyClass = Nothing End Sub End Class
Dim oLoadUnload Environment.Value("oLoadUnload") = New LoadUnload |
Making an object visible on a web page
Browser("百度一下,你就知道").Page("百度一下,你就知道").WebEdit("wd").Set "cora" Browser("百度一下,你就知道").Page("百度一下,你就知道").WebEdit("wd").MakeObjVisible Browser("百度一下,你就知道").CaptureBitmap "C:\Snap1.bmp",True Browser("百度一下,你就知道").Page("百度一下,你就知道").WebEdit("wd").Submit |
Advanced Text CheckPoints
?
Extending Test Objects using Classes
Class entendWebTable Private oWebTable Public Property Set Item(pObject) Set oWebTable=pObject End Property Public Property Let Item(pObject) Set oWebTable=pObject End Property Sub Click(Byval Row,ByVal Col) Set oCell=oWebTable._ WebElement("html tag:=TR","index:="&(Row-1)).WebElement("html tag:=TR","index:="&(Col-1)) oCell.click End Sub Sub ClickDOM(Byval Row,ByVal Col) Set oCell=oWebTable.Rows(Row-1).Cells(Col-1) oCell.click End Sub public Function GetCellData(Byval Row,ByVal Col) GetCellData=oWebTable.GetCellData(Row,Col) End Function public Function GetCellDataDOM(Byval Row,ByVal Col) GetCellData=oWebTableobject.Rows(Row-1).Cells(Col-1).outerText End Function
Public Function getColIndex(byval Col) If varType(Col)=vbString Then Col="Text:="&Col If oWebTable.WebElement("html tag:=TR","index:=0").WebElement("html tag:=TD|TH",Col).Exist(0) Then set oCell=oWebTable._ WebElement("html tag:=TR","index:=0").WebElement("html tag:=TD|TH",Col) getColIndex=oCell.GetROPProperty("attribute/cellindex")+1 else getColIndex=0 end if else getColIndex=Col End If End Function Function FindTextBySearch(Byval SearchText,ByVal matchIndex,ByRef Row,ByRef Col) ''.. End Function End Class
'method1 'Create a extend WebTable class object Set exWebTable=new entendWebTable Set exWebTable.item=Browser("..").Page("..").WebTable("..")
exWebTable.click 1,1 msgbox exWebTable.GetCellDataDOM(1,1)
'method 2 'registers the class as a function using the QTP RegisterUserFunc Public Function exWebTable(oObject) Set exWebTable=nothing Set exWebTable=new entendWebTable Set exWebTable.item=oObject End Function 'Register the entend function as one of the method for Webtable object RegisterUserFun "WebTable","Extend","exWebTable",true msgbox Browser("..").Page("..").WebTable("..").extend.GetCellDataDOM(1,1) |