Saturday, September 27, 2008

QTP Optional Step

QTP Optional Step


By default, QuickTest Professional deems steps that open the following dialog boxes or message boxes as Optional Steps:

Dialog Box / Message Box Title Bar

AutoComplete
File Download
Internet Explorer
Netscape
Enter Network Password
Error
Security Alert
Security Information
Security Warning
Username and Password Required

1. To COMPLETE a Run session an optional step is not necessarily required.

2.If a Step in an optional dialog box does not open, QTP avoids that step and continues ahead during a Run session. At the end of the Run session, a message is displayed for the step that failed to open the dialog box. Here remember that the step does not cause the Run to fail.

3. However if QTP does not find an Object from the optional step in the Object Repository, then the Run fails with an error message.

You can also add an optional step in the Expert View by adding OptionalStep to the beginning of the VBScript statement. For example:

OptionalStep.Browser("Browser").Dialog("AutoComplete").WinButton("Cancel").Click

This is an Optional step icon
A simple example for Optional Step:

1. Make sure that a new blank test and a blank Internet Explorer window is open.

2. In QTP click on Record in order to start recording.

3. Go to Start-> Programs-> QuickTest Professional->Sample Applications-> Flight.

4. Enter Username.

5. Enter Password.

6. Hit the enter key.

7. When the Flight application is open go to File->Exit.

8. Close the Internet explorer window also from the Cross button which is on the extreme top right..

9. Click Stop to stop the test recording.

In the Keyword view, follow the below steps:


Finally it looks like this


Now before you run the test make sure Internet Explorer window is NOT open.


The idea is when you run the above test without IE, it will not show any error message or fail, it will just bypass the ‘browser closing’ step as we have marked it Optional and it will ignore any error for the optional step. But it shows you the warning in the test results.


Try to run the same test by just removing the ‘Optional Step’ tag from the above lines and see that it will fail and show you the Run Error.

On Error Statement

On Error Statement


On Error statement enables or disables error handling.

Two On Error statements which we will discuss here are:

On Error Resume Next
On Error GoTo 0

If there is an error in the code "On Error Resume Next" ignores it and continues with the next line of the code.

Consider the below example. Write the below code in a notepad and save it as a .vbs file and run it from the command prompt. It works fine, but now if you comment or remove the "On Error Resume Next" line, it will show error because of the 7th line.

msgbox "Ha Ha 1"
call one
msgbox "Ha Ha 2"
Function one()


On Error Resume Next
msgbox "Function one Start"
two
msgbox "Function one End"

End Function
msgbox "Ha Ha 3"

Moreover "On Error Resume Next" is local to a function / procedure in which it is written. If it is written within a Function / Procedure then it will be in effect as long as the Function / Procedure executes and will be nullified (will not be in effect) when the Function / Procedure finishes execution.


msgbox "Ha Ha 1"
call one
msgbox "Ha Ha 2"
call two

Function one()


On Error Resume Next
msgbox "Function one Start"
happy
msgbox "Function one End"

End Function

Function two()


On Error Resume Next
msgbox "Function two Start"
happy
msgbox "Function two End"

End Function

"Ha Ha 3"

Run the above program, it will show the last message box "Ha Ha 3", but if you comment the "On Error Resume Next" of Function two() then you will not see the last message box "Ha Ha 3" because when the program finds the word "happy" in Function two() and no error handler, it raises a Type Mismatch error.

Note that with "On Error Resume Next" error is not corrected, just ignored, and an error message is not displayed.

Use On Error GoTo 0 to disable error handling if you have previously enabled it using On Error Resume Next.




Err Object
Whenever there is a run-time error in the program, the properties of an Err object are filled with the information that helps to identify and handle the error.

After an On Error Resume Next statement the Err object's properties are reset to zero or zero-length strings ("").

Because the Err object is an intrinsic (basic / its part of every vbscript project you create) object with global scope — there is no need to create an instance of it in your code. That is it does not need to be declared before it can be used.

Properties Purpose

Description Contains a string describing the error.
Number Contains the Error number. It is the default Property, means Err.Number is same as Err
HelpFile Contains path to the help file
HelpContext Its a Context ID within the helpfile. The HelpContext property is used to automatically display the Help topic identified

Source Contains a string expression that is usually the class name or programmatic ID of the object that caused the error.

LastDLLError Contains last error code generated by DLL;Available only on 32 bit windows systems.
Methods Purpose
Clear Clears all property settings of the Err object. [VBScript calls the Clear method automatically whenever any of the following statements is executed:
On Error Resume Next
Exit Sub
Exit Function ]
Raise Forces a run-time error of a given number to be generated.




msgbox "Ha Ha 1"
call one
msgbox "Ha Ha 2"
Function one()

msgbox "Function one Start"
happy
msgbox "Function one End"
End Function

Firstly, try to run the above code, when the program reaches the line which has 'happy', it will show Type Mismatch error.

Now run the below code which now has "On Error Resume Next" and Err object. This is just one of the million ways you can use Err object. You can also use Err number in conditional statements and loops etc to make the code more robust.

msgbox "Ha Ha 1"
call one
msgbox "Ha Ha 2"

Function one()


On Error Resume Next
msgbox "Function one Start"
happy
msgbox "Error number is = " & err.number & " and " & "Error Description = " & err.description
msgbox "Function one End"

End Function

QTP Recovery Scenario Examples

QTP Recovery Scenario


QuickTest Professional Recovery Scenarios are summarized in the below mentioned points with 3 "easy to understand" examples.


1)
With "Recovery Scenario Manager" you can

a) create and edit recovery files,
b) create and manage the recovery scenarios stored in those files.

2)
A unique icon corresponds to a recovery scenario that indicates its type.

3)
Each recovery scenario is represented by an icon that indicates its type.

4)
You are guided step-by-step, through the process of creating a recovery scenario by Recovery Scenario Wizard.

5)
You start by defining the trigger event. [4 trigger types are there Pop-up window, Object state, Test run error, Application crash]

Pop-up window :

QTP Recovery Scenario 1



NOTE: Below is just one of the many ways of creating a recovery scenario.

We get a pop-up window (like the one you see below) while opening some of the websites like www.rediff.com. In the example below we will make use of that pop-up dialog. We can use different Recovery Scenarios for different pop-up windows, but here I am just using one Pop-up window as an example.



I have divided this example into 3 parts (1. creating a test, 2. creating a function library and 3. creating a recovery scenario).

1.
Open QTP and Internet Explorer.
Click on Record in QTP in order to start recording.
In the address bar of IE type http://www.rediff.com
When rediff is open, type some text in the Search textbox e.g. 'I am doing a test on QTP'
Click on Search button


Browser("Browser").Page("Page").Sync
Browser("Browser").Navigate "http://www.rediff.com/"
wait(10)
Browser("Welcome to Rediff.com").Page("Welcome to Rediff.com").WebEdit("MT").Set "I am doing a test on qtp"
Browser("Welcome to Rediff.com").Page("Welcome to Rediff.com").WebButton("Search").Click

2.
Go to File->New->Function Library
A new Function Library will be open. Without writing anything in the Function Library (let it be empty), just Save it and close it.
We will create Recovery Function in accordance with the prototype syntax of the Pop-up window at the time of creating a Recovery Scenario.

3.
Go to Resources->Recovery Scenario Manager...
Recovery Scenario Manager window opens
Click on "New Scenario" icon to open Recovery Scenario Wizard.
Click Next.
From Select Trigger Event, choose Pop-up window. Click Next.
Now when the "Specify Pop-up Window Conditions" area is open, make sure the pop-up window is also open simultaneously with this
"Specify Pop-up Window Conditions" window, so that you can click on the hand icon and then click on pop-up window so as to fill the "Window title" and "Window text contains" fields. Click Next.
Recovery Operations area opens, Click Next.
Choose Recovery Operation as Function Call, click Next.
On the next screen, click on button on the right of "Function Library" dropdown to select the function library we created earlier.
Click "Define new function:" radio button and The function in the Function prototype will be:


Function RecoveryFunction1(Object)
msgbox "hello Function"
End Function


Click Next
In the Recovery Operation window uncheck "Add another recovery operation". Click Next.
In the Post-Recovery Test Run Options choose "Stop the test run" radio button. Click Next.
Give the Recovery Scenario a Name and Description and click Next
In the Completing the Recovery Scenario Wizard area check "Add scenario to current test" and click Finish.
In the Recovery Scenario Manager window you will see one scenario added in the scenarios area.
Click Close and save the Recovery Scenario.










Now Run the test. It should show message box with the message we wrote in function library while creating a Recovery Scenario.

In the second part of this example, instead of creating an empty function library we can write one function in it according to the appropriate prototype like the one below, which clicks the OK button on the Pop-up window.

Function Recovery_Example(Object)
'Returns a handle to a run-time object's window
win_handle=Object.GetROProperty("hwnd")
'Assigning an object reference to a variable
Set pop_win=Window("hwnd:=" & win_handle)
'Printing that object's title
Msgbox pop_win.GetROProperty("title")
'Clicking OK button on that object.
pop_win.WinButton("text:=OK").Click
End Function


Object state :


QTP Recovery Scenario 2






1)
This is an example of Object State trigger event.


Open QTP and Flight Reservation window.
Click Record in QTP in order to start recording.
Enter Date of Flight, Fly From, Fly To fields.
Click Flights... button. Flights Table opens. Click OK.
Enter Name and Click Insert Order.
After Insert Order is complete the Delete icon is enabled.

Now our Recovery scenario works if this delete icon is disabled (when its enabled property is False)

SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").WinEdit("Agent Name:").Set "sach"
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure "484190f7c6928cfbf4630e91eaf4d2901b3381e1"
Dialog("Login").WinEdit("Password:").Type micReturn
Window("Flight Reservation").WinObject("Date of Flight:").Type "090909"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Denver"
Window("Flight Reservation").WinComboBox("Fly To:").Select "Frankfurt"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set "sach"
Window("Flight Reservation").WinButton("Insert Order").Click
Window("Flight Reservation").WinButton("Button_2").Click
Window("Flight Reservation").Dialog("Flight Reservations").WinButton("No").Click
Window("Flight Reservation").WinMenu("Menu").Select "File;Exit"

2)
Go to File->New->Function Library
A new Function Library will be open. Without writing anything in the Function Library (let it be empty), just Save it and close it.
We will create Recovery Function in accordance with the prototype syntax of the Pop-up window at the time of creating a Recovery Scenario.

3)
Go to Resources->Recovery Scenario Manager...
Recovery Scenario Manager window opens
Click on "New Scenario" icon to open Recovery Scenario Wizard.
Click Next.
From Select Trigger Event, choose Object State. Click Next.
In Select Object area, click on hand and then click on the Delete icon on the Flight Reservation window.
Click OK in "Object Selection - Object State Trigger" window. Click Next.
Set Object properties and Values window opens. Click Add/Remove..button
In the Edit Properties window, check only window id and enabled and click OK.
Edit the enabled property to False. Click Next
Again click Next in Recovery Operations area.
Choose Recovery Operation as Function Call, click next.
On the next screen, click on button on the right of "Function Library" dropdown to select the function library we created earlier.
Click "Define new function:" radio button and The function in the Function prototype will be:

Function RecoveryFunction1(Object)
msgbox "hello Function"
End Function

Click Next
In the Recovery Operation window uncheck "Add another recovery operation". Click Next.
In the Post-Recovery Test Run Options choose "Stop the test run" radio button. Click Next.
Give the Recovery Scenario a Name and Description and click Next
In the Completing the Recovery Scenario Wizard area check "Add scenario to current test" and click Finish.
In the Recovery Scenario Manager window you will see one scenario added in the scenarios area.
Click Close and save the Recovery Scenario.

To see the recovery scenario working, try to run the test with lines 6 to 12 of the code in section 1 (line which types date to the line which clicks Insert Order button) commented.


Test run error :

QTP Recovery Scenario 3





1)
Make sure Flight Reservation window is open.
Fill Date of Flight, Fly From and Fly To fields.
Click Record in QTP in order to start recording.
Click on the Flights button in the Flight Reservation window.
When the Flights Table window opens click on OK.
Click stop in order to stop recording.

Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click

2)
Go to File->New->Function Library
A new Function Library will be open. Without writing anything in the Function Library (let it be empty), just Save it and close it.
We will create Recovery Function in accordance with the prototype syntax of the Pop-up window at the time of creating a Recovery Scenario.

3)
Go to Resources->Recovery Scenario Manager...
Recovery Scenario Manager window opens
Click on "New Scenario" icon to open Recovery Scenario Wizard.
Click Next.
From Select Trigger Event, choose Test run error. Click Next.
In "Select Test Run Error" area, choose "Object is disabled" from Error dropdown. Click Next.
Recovery Operations area opens, Click Next.
Choose Recovery Operation as Function Call, click next.
On the next screen, click on button on the right of "Function Library" dropdown to select the function library we created earlier.
Click "Define new function:" radio button and The function in the Function prototype will be:


Function RecoveryFunction1(Object)
msgbox "hello Function"
End Function




Click Next
In the Recovery Operation window uncheck "Add another recovery operation". Click Next.
In the Post-Recovery Test Run Options choose "Stop the test run" radio button. Click Next.
Give the Recovery Scenario a Name and Description and click Next
In Completing the Recovery Scenario Wizard area check "Add scenario to current test" and click Finish.
In the Recovery Scenario Manager window you will see one scenario added in the scenarios area.
Click Close and save the Recovery Scenario.



Now when you Run the test make sure in the Flight Reservation window you go to File->New Order, so as to empty all fields and disable Flights button to see if the Recovery Scenario is triggered when the object is disabled.



6)
After that you specify the recovery operation(s) [Recovery Operation can be Keyboard or mouse operation, Close application process, Function call, Restart Microsoft Windows]

When using Function call, Functions have to be defined using a prototype syntax, which is different for each trigger type.(See QTP User Guide.)

7)
Then you select a post-recovery test run operation. [Which can be Repeat current step and continue, Proceed to next step, Proceed to next action or component iteration, Proceed to next test iteration, Restart current test run, Stop the test run]

8)
The recovery file is saved in the specific location with the file extension .qrs.

9)
Properties for any defined recovery scenario can be viewed from Recovery Scenario Properties dialog box

10)
During the run session, QuickTest ignores deleted recovery scenario that is associated with a test or component.

11)
You can copy recovery scenarios from one recovery scenario file to another.

12)
The scenarios can be prioritized so that QuickTest applies the scenarios during the run session in a order of priority.

13)
Some or all of the scenarios can be disabled.

14)
Recovery Scenario(s) can be set as default for all new tests.

15)
Go to File > Settings, the Test Settings dialog box opens. Select the Recovery tab.

You can edit a recovery scenario file path by clicking the path once to highlight it, and then clicking it again to enter edit mode.

16)
In the Recovery tab itself you can define when the recovery mechanism is activated:

On every step.
On error
Never.

17)
You can use the Recovery object to control the recovery mechanism programmatically during the run session.

QTP Regular Expression Examples

QTP Regular Expression


Objects and text strings with varying (changeable) values can be identified by QuickTest using Regular expressions.

Regular expressions can be used:


to define property values of an object.

to parameterize a step.

to create a checkpoint with changeable values.





Important points regarding Regular expressions:

You can use regular expressions only for values of type string.

When any special character in a regular expression is preceded by a backslash (\), QuickTest searches for the literal character.

You can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in a programmatic description.

For more common options to create Regular Expressions, see QTP User Guide.


Instead of writing more about QTP regular expressions, lets quickly jump to examples.




Below you will find examples of :

QTP Regular Expression Example 1



[This is just an example using Yahoo mail inbox. Your inbox unread mails may differ from the one shown in this example]

1. Launch QTP and open a new test.

2. Open Internet Explorer.
[Now we have QTP with a blank test and Google open.]

3. Click on Record in order to start recording.

4. Copy and paste this URL (https://login.yahoo.com/config/login_verify2?&.src=ym) in the browser's address bar to open Yahoo mail login.

5. Type your user name and password to login to Yahoo mail.

6. When Yahoo mail is open, click on the Inbox link as shown in the screenshot below.



7. Click on Stop in order to stop recording.
My recorded code looks like this:

Browser("Browser").Page("Page").Sync
Browser("Browser").Navigate "https://login.yahoo.com/config/login_verify2?&.src=ym"
Browser("Browser").Page("Yahoo! Mail: The best").WebEdit("login").Set "sach2n"
Browser("Browser").Page("Yahoo! Mail: The best").WebEdit("passwd").SetSecure "4801a2cbf793b46aad67194b5cbc961c071f"
Browser("Browser").Page("Yahoo! Mail: The best").WebButton("Sign In").Click
Browser("Browser").Page("Yahoo! Mail - sach2n@yahoo.com").Link("Inbox (6)").Click

Now if you don't check any mail in your inbox and log out and then again run this code it will work fine.
But if you check any mail like if I check one mail in my inbox then it will be Inbox(5) in the above screen shot, then if I run this code it will fail and show the below error.



Now we will change the above code with the help of regular expression so that it will work even if there is only one unread mail.

In QTP go to Resources (menu) ->Object Repository.

Object Repository window will open. Now follow the screen shots below.





When you click on the button as in above screen shot it will open 'Value Configuration Options' window. On this window click on Regular Expression check box. When you click on checkbox it will show warning as in the screen shot below. Just click on Yes.






Now in the Constant text box (above screenshot) enter what I have entered "Inbox \([5-6]\)" and click Ok and close Object Repository window.

This Regular Expression setting which we have done works for inbox unread mails between 5 and 6 e.g. if your inbox says inbox(5) or inbox(6).

Run the test. It passes for me because I had 5 unread mails in my inbox (inbox(5)).

You can do this setting according to your convenience e.g. [1-5] for unread mails between 1 and 5 and so on.



QTP Regular Expression Example 2



1. Open QTP and a new test.

2. Open Internet Explorer and open this URL http://www.worldtimeserver.com/current_time_in_IN.aspx

3. Click on Record in order to start recording.
4. Go to Insert-> Checkpoint->Text Checkpoint.

5. QTP will be minimized and mouse pointer will change into hand shape.

6. Click on time as shown in below screenshot.



7. Text Checkpoint Properties window will open with the text on which we clicked on, in red color.

8. In this window, on the right hand side of 'Constant' radio button click on pencil and paper button to open "Constant Value Options" button.

9. Check Regular Expression checkbox and in the value field type:(1[012]|[1-9]):[0-5][0-9] (am|pm) . Click OK. Again click Ok to come out of Text Checkpoint Properties window.

10. Click on Stop in order to stop recording.

It will record only one line in the expert view:

Browser("India current local time").Page("India current local time").Check CheckPoint("India current local time from WorldTimeServer.com")

Now you can refresh that website so as to see the current time and run this test again. It should pass.
QTP Regular Expression Example 3



1. Open QTP and a new test.

2. Open Internet Explorer and open this URL http://www.worldtimeserver.com/current_time_in_IN.aspx

3. Click on Record in order to start recording.

4. Go to Insert-> Checkpoint->Text Checkpoint.

5. QTP will be minimized and mouse pointer will change into hand shape.

6. Click on time as shown in below screenshot.



7. Text Checkpoint Properties window will open with the text on which we clicked on, in red color.

8. On the right hand side of 'Parameters' radio button, click on that pen and paper icon, to open Parameter Options dialog box.

9. Make sure Parameters Type is Data Table. In the Advanced Configuration area click on Regular Expression checkbox. Click Ok. Again click ok to come out of Text Checkpoint Properties window.

10. Click Stop in order to stop recording.

In the expert view it will write this code:

Browser("India current local time").Page("India current local time").Check CheckPoint("India current local time from WorldTimeServer.com")

In the global data sheet it will add a new column heading "India_current_local_timeChecked_Text" and will add in the first row- the current time. Now in place of this current time enter this (1[012]|[1-9]):[0-5][0-9] (am|pm) and save it.

Run the test. It should work fine.

QTP Script to create file

QTP Script to create file


Now lets do some kind of processing with file system e.g. working with text, excel, word etc files from within the QTP.

For this tutorial you need to know VBScript FSO (File System Object).

The main purpose of the FSO is to access the file system of the computer.

File System Object model is:


or some people make it like this:
These above objects have methods and properties. With these above objects you can obtain and work with the information about drives, folders, files etc like creating a new file, opening a file, writing into a file and much more.

Here we will see a very simple example how to create a text file from within QTP.

Dim fso, new_file
Set fso = createobject("scripting.filesystemobject") // an instance of filesystemobject is being created here. After an instance (fso) is created then we can use the methods (like createtextfile, CreateFolder etc) with that objects instance.
Set new_file = fso.createtextfile("c:\testfile.txt", True) //createtextfile is a
method to create a file and after creating a file it returns a TextStream object
that can be used to read from or write to the file.
new_file.writeline("hello world!")
new_file.close

Just write the above text in the expert view of a new blank test and run it. A new text file (testfile.txt) will be created with "hello world!" written in it.

Try to change the extention of testfile.txt to testfile.doc and see what happens.

Much more to come, keep glued.

QTP Importing Database Table Example

QTP Importing Database Table

For this tutorial make sure you completed the Database checkpoint tutorial successfully. Because the connection we made in that tutorial with the oracle will be used here.

It is very simple to import data from database into Data Table.

Right-click somewhere inside the data table.

Go to Sheet->Import->From Database...
"Database Query Wizard" opens.

Click on the radio button "Specify SQL statement manually".

(make sure that "Maximum number of rows" checkbox is NOT checked)

Click Next

Click Create button.

"Select Data Source" window opens

Click "Machine Data Source" Tab

Select Oracle from there and click ok.

Enter password for oracle in the "Oracle ODBC Driver Connect window"

After entering password when you click on ok, it open "Database Query Wizard" window with 'Connection string' automatically filled with info like DSN, UID etc.

Enter SQL statement "select * from emp;" in SQL statement Box.

Click Finish and lo the data is there in the data table.

QTP Reusable Actions Example

QTP Reusable Actions


In this tutorial we will see how to use more than one action in a test and how to call one action from another with in the same test.

Open a blank test. By default it will have Action1 in it (make sure you are in
the keyboard view).

Make sure that Action1 is selected/highlighted and click on the Expert View tab.

In the Expert View type:
msgbox ("my action 1")

Again when you go to keyword View and expand Action1 it will show you function call under it.

In that keyword View itself go to Insert (Menu) ->Call to New Action. 'Insert Call to New Action' Dialog box opens with Action2 as a default name of a new action. By default it will be added at the end of the test as this radio button is selected in the location area.

Click ok.

It will add Action2 to your test.

Make sure that Action2 is selected and click on the Expert View tab.

In the Expert View type:
msgbox ("my action 2")

Similarly insert a third Action.

After third action is added, select Action1(keyword view), right click on it and choose 'Action Properties'.

In the Action properties window that opens, check the 'Reusable action' checkbox at the bottom.

Click ok.

Now again highlight Action3 right click on it and choose 'Insert Call to Existing action'.

'Select action' dialog box appears. In this dialog box in the 'action' dropdown box it will have Action1 by default since we made only that action as reusable.
Just click ok.

In the keyword View where you can see all the three actions, make sure against Action3 it shows "Call to Action1 action" under Documentation.

Run the test. Three message boxes appear in succession showing 'my action 1', 'my action 2', and again 'my action 1'.