Automation Testing with QTP

Description:   ''This example starts QuickTest, opens a new test, and adds a new action, which calls a second action.Then it edits the first action's script to move the call to the second action to a new position in the script,validates the syntax of the new script, defines some action parameters, and uploads the modified action script.”

Dim qtApp, ActionContent, ActionName, ActionDescr, NewAction, SecondAction, script

Below line of code creates an object of the Class Application for the QuickTest Software
Set qtApp = CreateObject("QuickTest.Application") ' Create the application object
qtApp.Launch
qtApp.Visible = True
qtApp.New
 In the above line of code just the environment is getting created and then on we can start with the scenarios. qtApp is the instance of the QTP that will be used.

ActionContent = "Window(""Calculator"").WinButton(""1"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""+"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""+"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""="").Click"
ActionDescr = "A new sample action for the test."
ActionName = "Action" + CStr(qtApp.Test.Actions.Count + 1)

CStr is a vbscript function that is used to change any content into string.

Add a new action at the beginning of the test
Set NewAction = qtApp.Test.AddNewAction(ActionName, ActionDescr, ActionContent, False, qtAtBegining)

Here what is being done is instance of the QTP application is availed in qtApp variable as initialized above and in that instance a class named Test which is actually automated Project name in the current context, and then on we add a method name which is different from a function “AddNewAction” : It can be termed as a set of events that may be used by some other events within the project.

Do remember that in oreder to make an Action to be reusable the property must be assigned as reusable, also in case we want to call it from outside the current project, it needs to be defined as Global which has also been discussed in prior posts.

What we do here is Add another action and call it from the beginning of the action that was just added above.

ActionContent = "Function f1(str)" & vbCrLf & vbTab & "msgbox str" & vbCrLf & "End Function"
ActionName = "Action" + CStr(qtApp.Test.Actions.Count + 1)

Set SecondAction = NewAction.AddNewAction(ActionName, ActionDescr, ActionContent, True, qtAtBegining)
qtApp.Test.AddNewAction was used in the previous action creation code.
NewAction.AddNewAction is being used in this very action creation code.

Now we will be using  the Load Script function to store the content of the first new action into the script array
script = Load_Script(NewAction.GetScript())
script = Move_CallAction(script, SecondAction.Name, UBound(script))
ActionContent = Save_Script(script)
scriptError = NewAction.ValidateScript(ActionContent)

'Converts script array to the text
'Sets new script source to the action
Load_Script, Move_CallAction, Save_Script  are user defined function as is availed below after some more logical coding.

Now the below code needs to be called
If Len(scriptError) = 0 Then
    NewAction.SetScript ActionContent
    NewAction.Description = "Check the calculator application and run next Action"
    NewAction.Type = "Reusable" 'Put Reusable type to the new action
    Set aParamDefs = NewAction.ActionParameterDefinitions
    aParamDefs.Add "InParam", "An input action parameter definition", 0, 0, "Input Value"        
    aParamDefs.Add "ResParam", "An output action parameter definition", 0, 1, "Output Value"
    Set resParamDef = aParamDefs.Item ("ResParam")
    resParamDef.Type = 1 'Put the boolean parameter type
    resParamDef.DefaultValue = false
    resParamDef.Description = "Result parameter"
Else
    Err.Raise E_SCRIPT_NOT_VALID, "Validate Script Error", scriptError
End If

Const E_SCRIPT_TABLE = 1
Const E_EMPTY_SCRIPT = 2
Const E_SCRIPT_NOT_VALID = 3

Const is the keyword available with VBScrip which can be used to assign values to variables that can not be overloaded with any other re initializations. Generally we use it in Sheet names and other environment variable names.
·         Public Function Load_Script(src)
If Len(src) = 0 Then
Err.Raise E_SCRIPT_TABLE, "Load_Script", "Script is empty"
End If
Load_Script = Split(Trim(src), vbCrLf)
·         End Function
Len is used to return the length of the string within the parameters. It is in built function with VbScript.
Split is another function name which is used to sub divide a string into individual elements based on separator mentioned [in this case vbcrlf ] and get it stored in an array format.
Trim is a yet another function which is used to remove any extra space that might be preceding or suffixing the string in this case src. Such as a string “  vip  ” string becomes trim(“  vip  ”) as “vip”.
We do have Ltrim & Rtrim functions to remove spaces only from left side or right side, ahich can be used as suits our requirement.
·         Public Function Save_Script(script)
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Save_Script", "Script should be string array"
End If
If UBound(script) - LBound(script) = 0 Then
Err.Raise E_SCRIPT_TABLE, "Save_Script", "Script is empty"
End If
Save_Script = Join(script, vbCrLf)
·         End Function

IsArray is a function that checks if the parameter within braces is an array or not, an according returns as true or false which is VbScript is denoted as 1 or 0. 
UBound and Lbound gives the boundary value of the array index to which the resulting array from the string broken up results. Suppose the array size after string split is 78, then Lbound is 0 and UBound is 77.
Join as the name suggests joins the two strng just like a concatenation operator.

Find_Line, Move_Line,Insert_Line,Delete_Line are some of the functions which will help us demonstrate our conceptual clarity to play with QTP and make ourselves empowered to create any automated testing execution flow with ease, with perfection.
·         Public Function Find_Line(script, criteria)
Dim rExp, I
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Find_Line", "The script should be a string array"
End If
Set rExp = New RegExp
ptrn = ""
If IsArray(criteria) Then
ptrn = Join(criteria, " * ")
Else
ptrn = criteria
End If
rExp.Pattern = ptrn 'Set pattern string
rExp.IgnoreCase = True ' Set case insensitivity.
rExp.Global = True ' Set global applicability.
I = 0
For Each scrItem In script
If rExp.Execute(scrItem).Count > 0 Then
Find_Line = I
Exit Function
End If
I = I + 1
Next
Find_Line = -1
·         End Function

Find_Line  is a function that has a certain return type. We have two types of methods which is of profound interest to our requirement , one being the SubRoutine, and the other being Function . The only difference being that the SubRoutine has no return type and has the keyword Sub prefixed, and the latter Function has the keyword Function associated to it, and has some return values associated with it. In this case the return type being the value 0 or 1 in accordance with the code execution.
Having already discussed about IsArray & join we do not need to revisit it here .
For each Next block is something that is used as a looping control block to execute some loop for our business requirement or in this case just to visit to each index within the array.
Regular expression is something new we have come to in this very code block. It is used to create some sort of pattern matching for our requirements to be addressed with ease. For simple context suppose in a website we have to fill in an e-mail id, so there needs a validation to be performed as to whether the entered e-mail id is in correct format or not. A sort of pattern matching is needed in this context. The same is being done when we do in above code block.
New RegExp is the instantiation of the regular expression that is used to be met.

For each scrItem in Script means that for each index value in the array Script we have some looping that occurs, and the code is indeed self descriptive enough to us.

ExitFunction is the keyword that is used to exit from the execution of the Function block as and whne such condition is met. Similar is the use of ExitFor, ExitIf,ExitWhile.

·         Public Function Move_Line(script, curPos, newPos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Move_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If curPos = newPos Or curPos < 0 Or newPos < 0 Or scrLen < curPos Or scrLen < newPos Then
Move_Line = script
Exit Function
End If
tmpLine = script(curPos)
If newPos > curPos Then
For curPos = curPos + 1 To scrLen
script(curPos - 1) = script(curPos)
If curPos = newPos Then
script(curPos) = tmpLine
Exit For
End If
Next
Else
For curPos = curPos - 1 To 0 Step -1
script(curPos + 1) = script(curPos)
If curPos = newPos Then
script(curPos) = tmpLine
Exit For
End If
Next
End If
Move_Line = script
·         End Function

In the function Block Move_Line , we have just reused the functions that were used in the previous function and introduced some new keywords which work in accordance with what we discussed earlier, such For Next loop , If Else condition block, For next with negative iteration as well by using the Keyword Step-1 to customize a back loop with 1 decrement, same can be altered by step-2 and so on and so forth. One binary operator is used “OR” which is same as we might have had acquaintance in the Digital Circuit Gate circuit creation. It equate to true if at least one condition evaluates to TRUE. We have similar Keyword available in AND wherein both needs to be TRUE to make the evaluation return the value as TRUE.

·         Function Insert_Line(script, lineSrc, linePos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Insert_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If (scrLen = 0 And linePos <> 0) Or (linePos > scrLen + 1) Then
Insert_Line = script
Exit Function
End If
newScript = Split(String(scrLen + 1, " "), " ")
shiftIndex = 0
For I = 0 To scrLen + 1
If linePos = I Then
newScript(I) = lineSrc
shiftIndex = 1
Else
newScript(I) = script(I + shiftIndex)
End If
Next
Insert_Line = newScript
·         End Function
In the function above for Insert_Line we do not have much of an indifference to the prior code except for the introduction of the operator Not Equal to which is symbolically represented as “<>”.

·         Function Delete_Line(script, linePos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Delete_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If (scrLen = 0) Or (linePos > scrLen) Then
Insert_Line = script
Exit Function
End If
If scrLen = 1 Then
Delete_Line = Array()
Exit Function
End If
newScript = Split(String(scrLen - 1, " "), " ")
shiftIndex = 0
For I = 0 To scrLen
If linePos = I Then
shiftIndex = 1
Else
newScript(I - shiftIndex) = script(I)
End If
Next
Delete_Line = newScript
·         End Function
Similar is the code creation as has been already discussed , with nothing new coming into picture. Split is being done for the string, and the separator in this case is blank space.

·         Public Function Move_CallAction(script, actName, newPos)
curPos = Find_Line(script, Array("RunAction", """" & actName & """"))
Move_CallAction = Move_Line(script, curPos, newPos)
·         End Function

Move_CallAction is the main controller within this module as is clearly visible from the above code block. Having read through the complete article carefully and patiencely anyone could have figured out how the control flow can be regulated. I hope the code is self explanatory and at times I have chipped in with some comments which can be definitely understood without much of a hara kiri.

1 comment: