Tuesday, October 9, 2012

On Error Resume Next

   Hello All! Happy to be in touch with you all through this blog. In this post, we are going to see a way of error handling. On many occasions, the execution has stopped if any error occurs during exection. But in some case, we wanted to continue the execution even if any error occurs. QTP supports certain methods which allow scripts to run even if certain errors occurred.

On Error Resume Next

We need to include 'On Error Resume Next' at the beginning of the script or before the step in which we are anticipating some errors. This command will handle the error and continue the execution of the script.

Considering the below script, I know the value of 'a' but the value of 'b' is not constant and it may change based on other steps in the script.

a = 10
b = <Dynamic value>
Msgbox a/b

If the 'b' value is '0' then 'Division by Zero' error will be displayed. In this situation, we can add error handling command to handle this.

On Error Resume Next
a = 10
b = 0
Msgbox a/b
If Err.Number <> 0 Then
 Msgbox Err.Description
End If


With this example, the error will be handled and the actual error message will be displayed in the message box. The script will continue to execute without showing error/exit.

Now, we have activated this feature and If we don't want to have this enabled further, we can deactivate this error handling feature by below command.

On Error Goto 0

Putting all to gether,

On Error Resume Next
a = 10
b = 0
Msgbox a/b


If Err.Number <> 0 Then
 Msgbox Err.Description
End If


On Error Goto 0
Msgbox a/b


While executing this script, when first time error occurs it will be displayed in the Message box. Because at the first step we enabled the error handling feature. At the 10'th step we disabled this feature. So error will not be handled for all the steps that executed after Step 10.


Thursday, October 4, 2012

ExecuteFile function


   Hello! ExecuteFile is a VB script function which is used to execute any VBS (VB Script) file. It is also used to dynamically mapping a VBS file to a test.

Syntax : ExecuteFile "FileName with Path"

Example : ExecuteFile "C:\Test.VBS"

   You may ask that why do we have to use ExecuteFile function instead of mapping an VBS file to the Test. It depends on the situation and based on the use of the VBS file.

   Say for Instance, we have library (VBS) file which contains all common functions for a Test. It is important to note that this VBS file may required any part of the test as it contains all the common functions. So it is always better to map the VBS file to the test. All the library files that mapped to the test will be executed at the beginning of the exection.

   There may be a different case in which it is required to exectue a VBS file only on a specific scenario or a step. In this case, we can use ExecuteFile method to execute the script at the required step.

Wednesday, September 5, 2012

Creating MS WORD document using QTP

Hello! Here is the script to create a word document and write some text in the created word document.

'Create a Word document
 Set oWord = CreateObject("Word.Application")
 Set oDoc = oWord.Documents.Add
 oWord.Selection.TypeText "Test document created by QTP."
 oWord.ActiveDocument.SaveAs "C:\Test.doc"
 oDoc.Close
 oWord.Quit

We can also align the text that is to be writed in the word document. Check out the script below

'Create a Word document
 Set oWord = CreateObject("Word.Application")
 Set oDoc = oWord.Documents.Add
    With oWord.Selection
     .EndKey 6,0
     .TypeParagraph()
     .Font.Size ="10"
     .Font.Name = "Arial"
     .Font.Color = RGB (0,100,0)
     .Font.Bold = True
     .Font.Underline = False
     .Font.Italic = False
     .TypeText "Test document created by QTP."
 End With
 oWord.ActiveDocument.SaveAs "C:\Test.doc"
 oDoc.Close
 oWord.Quit


We will see how to adding tables in to word document in another post.

Tuesday, August 14, 2012

File Handling operations - QTP

   Hello All! In this post, we going to see about File handling in QTP. The term file handling is seem to be confusing rite? Don't get confused, it's just a text file or in other words flat files.

   In order to handle text files using QTP, we need to create below object. Without creating object of "Scripting.FileSystemObject" we cannot read/write text files.

Set FSO = CreateObject("Scripting.FileSystemObject")

Creating Text File:

Syntax : FSO.CreateTextFile (FileName, [In, Optional] Overwrite, [In, Optional] Unicode)
FSO.CreateTextFile ("C:\abc.txt",False,False)

The file "abc.txt" will be created in "C:\" drive when executing the above line. But make sure the file does not exists in the directory already. Make the Overwrite parameter as True, if you want to create a file by overwritting the already exiting file.

Open Text File:

Syntax : FSO.OpenTextFile (FileName,[in, optional] IOMode, [in,optional] Create, [in,optional] Format)

FileName Required. The name of the file to open.

IOMode Optional. How to open the file
1=ForReading - Open a file for reading. You cannot write to this file.
2=ForWriting - Open a file for writing.
8=ForAppending - Open a file and write to the end of the file. 

Create Optional. Sets whether a new file can be created if the filename does not exist. True indicates that a new file can be created, and False indicates that a new file will not be created. False is default
Format  Optional. The format of the file
0=TristateFalse - Open the file as ASCII. This is default.
-1=TristateTrue - Open the file as Unicode.
-2=TristateUseDefault - Open the file using the system default.

Set file1 = FSO.OpenTextFile("C:\abc.txt", 1, True)

The file 'abc.txt' will be opened in 'Read' mode if it exist. If the file does not exist then a new file will be created and the created file will be opened in the read mode.

Check if File Exists:

Syntax:
FSO.FileExists(FileSpec)
Msgbox FSO.FileExists("C:\abc.txt")

This will return True if the file exists and False if does not.

Monday, July 16, 2012

QTP - Dictionary Object


   QTP Supports Dictionary objects which will be used to store data in a Key & Item combination. Dictionary object is one of the feature of VB Script.We can read the Item from the dictionary object using the key. Also, dictionary objects support various operations for storing data effectively. we can even say dictionary objects are another form of dynamic array which becomes more handy than array.

Creating Dictionary Objects:
Dim oDict
Set oDict = CreateObject("scripting.dictionary")

We can create dictionary object using CreateObject method. In the above example oDict is the dictionary object created.

Adding values to Dictionary Object:

oDict.Add "Key1","Item1"
oDict.Add "Key2","Item2"

Read a item from Dictionary Object:

Msgbox oDict.Item("Key1")

Using Item method, we can read the item corresponding to a key.
"Item1" will be retrieved when executing the above line.

Read all items from Dictionary Object:

For each vItem in oDict.Items
   msgbox vItem
Next


Removing a key from Dictionary Object:

oDict.Remove ("Key1")

When executing the above the line, the "Key1" key along with it's item will be removed from the Dictionary.

Removing all keys from Dictionary Object:
oDict.RemoveAll

Changing a key in Dictionary Object:

oDict.Key("Key1") = "Key3" 'Set key for Key1 to Key3
Msgbox oDict.Item("Key3")


In the above lines, we are assigning/changing the 'Key1' to 'Key3'. In the Msgbox 'Item1' will be displayed as it's corresponding Key name is changed to 'Key3'.
If you read all the keys from the Dictionary then 'Key3' & 'Key2' will be retrieved and there won't be any key with 'Key1' name as it's changed.

Well, we have already seen how to read all the Items from the dictionary. Here is the script to read all the Keys from the dictionary.

For each vKey in oDict.Keys
 msgbox vKey
Next


You are having a question rite? I am able hear that you are asking whether Dictionary objects supports to check if a specific key is present in the dictionary or not. Here is the way to do that..

Msgbox oDict.Exists("Key3")      'It will Return True
Msgbox oDict.Exists("Key1")      'It will Return False


It will return either True/False based on the presence of the Key in the dictionary.
Also, we can get the count of the key/Item pair exists in the dictionary.

Msgbox oDict.Count   'It will Return 2

One more advantange of dictionary object is that we can use any number of dictionary objects in our script and we can have any number of items in the dictionary as well. How easy and useful this dictionary object is!!!  Well, we can create nested dictionary object also which we will see in another post.. :)

Wednesday, July 4, 2012

Using VBS file in QTP


     Hello All! In this post we are going to see how to execute VBS files in QTP. Before getting started, VBS is a VBScript file contains block of VBscript that will be used by QTP Tests.  In most cases, we will be having the user defined functions and global variables in VBS files.

     There are two ways by which we can execute VBS files using QTP. One simple way is that add the VBS files to the resources list of the test. By doing so, all the VBS files assicated as resources will be executed when we start the QTP Test execution.

To Add VBS to Resources:
1. Select File - > Settings
2. In Test Settings dialog, select 'Resources' tab.
3. Click on the "+" symbol and add the VBS files to resources.

   The second method is "ExecuteFile" function.
Syntax:
ExecuteFile "<VBS File Name with Path>"
Ex:
ExecuteFile "C:\Test.VBS"

We can use ExecuteFile method to load a VBS file during run time. Where as the first method will be used to execute the VBS files when the QTP Script execution starts.

Saturday, June 30, 2012

Connect QC through API

Here is the script to connect to QC through API.

DomainName =”TEST”
ProjectName =”Automation”
UserName =”Ramesh”
Password =”Password″
ServerName =”Server:8080″
Set objTDConnection = CreateObject(“TDApiOle80.TDConnection.1″)

QCServerName =”http://”& ServerName &”/qcbin”
objTDConnection.InitConnectionEx QCServerName
objTDConnection.ConnectProjectEx DomainName, ProjectName, UserName, Password
If objTDConnection.loggedin Then
    msgbox “Connect successfully “
else
    msgbox “not connect with Quality Center Check username /Password/Domain name /Project Name “
End If

Set objTDConnection = nothing

Thursday, June 14, 2012

Function - RegisterUserFunc

   
    In this post, we are going to see how to use RegisterUserFunc function. QTP Supports to register custom functions for a object. To make it more clear, we can create our own function for an object/ Test Object Class and we can register the function. So, these custom functions will be registered with object's function list.

Syntax:
RegisterUserFunc (TOClass, TOMethodName, FunctionName, <Optional> SetAsDefault)

Lets see how to use this function with an example. We are going to create our own function to set a value in  the text box. 

'Function Name : SetValue
'Parameters : obj, newValue
'Description : To set a value in the text box
'Author : Ramesh
Function SetValue ( obj, ByVal newValue)
   obj.Set newValue
   Reporter.ReportEvent micPass, obj.GetRoProperty("name"), "Value Entered : " & newValue
End Function

So now our function to set value in to a text box is ready!. We have to register the function to use it.

RegisterUserFunc "WebEdit", "NewSet", "SetValue",True

Here, we are registering the function "SetValue" for the "WebEdit" object class with the name "NewSet". The last parameter "True" will set the registering function as a default function. The keyword 'NewSet' has been registered with the WebEdit class. If we place a dot after WebEdit object, "NewSet" will also be listed in the context menu.We have registered the function and lets see how to use the registered function.

Browser("Mercury Tours").Page("Mercury Tours").WebEdit("userName").NewSet "UserName"

We are using 'NewSet' method instead of 'Set' to enter value in text box which inturn call our custom created function. One important thing need to be keep in mind is that a function should be registered before accessing it. It will be safer if we have all our RegisterUserFunc scripts in the Function library instead of directly place it along with action scripts.

Here is the block of script that can directly executed to see the results!!!! 

'Registering User Function 'SetValue'
RegisterUserFunc "WebEdit", "NewSet", "SetValue",True

'Function Name : SetValue
'Parameters : obj, newValue
'Description : To set a value in the text box
'Author : Ramesh

Function SetValue ( obj, ByVal newValue)
   obj.Set newValue
   Reporter.ReportEvent micPass, obj.GetRoProperty("name"), "Value Entered : " & newValue
End Function

'Set Value in to userName Text box
Browser("Mercury Tours").Page("Mercury Tours").WebEdit("userName").NewSet "UserName"


Also, Please note that If we are registering a function with already existing method name, then custom function will over ride existing method. Say for Instance, If we register with 'Set' method name , then existing set method will be override by custom / User defined function.
RegisterUserFunc "WebEdit", "Set", "SetValue",True


Thursday, May 31, 2012

Actions in QTP

  Happy to see you through this article. Actions!.. The name itself explain what it's going to do. Well, Actions are block of script that going to perform a specific action or operation in a test. We can rather say an Action is a function but actions have it's own object repository and DataTable sheet. A test may contain more than one action. An automation tester can decide what are all the events should be put in a action. Even though it's not complex, this single post is not enough to explain everything about Actions. Let me try to furnish as much as details I could accomodate in this post.
There are two types of Actions in common.
     1.  Reusable Action.
     2.  Non- Reusable Action.

 
Reusable Action:
    These actions can be reused in any place in the test. We can call the reusable action from another action. To mark an action as reusable, select the 'Reusable action' checkbox in the action properties. If we uncheck 'Reusable action' Checkbox it will become Non-Reusable action.


Non-Reusable Action:
   These actions can not be reused. We cannot call a non-reusable action from another action.





Creating an Action / Call to an Action :
    In QTP, we can create a new action, copy another action from different test/same test or we can create a call to exiting action in different test/same test.
Call to New Action...:
   Through this way we can create a new action. Also, It will create a call to new action from the action it's being created. We can either select "Call to New Action..." option from toolbar or from Insert menu. This will open the 'Insert Call to New Action' dialog. If we select 'Reusable Action' checkbox then the new action going to be created will be a resuable action.
There are two more options to choose where the call for the new action to be inserted.
  After the current step - Call to the new action will be created after the current step in the current action. So while executing the test, New Action will execute after current step.
  At the end of the test - Call to the new action will bve created at the end of the test. So New action will be executed after the execution of all the existing action.


Call to Copy of Action...:
  We can use this option when we want to create copy of an action (The copied action present in the current test directory). We can copy the action either from the same test or from another test. This option will create a copy of the action in the current test. Any changes in the copied action will not affect the original action.
   When selecting the 'Call to Copy Action..' option, "Select Action" dialog will be opened. By default, all the actions associated with the current test will be listed.
   If we select "Edit new action properties" check box in 'Select Action' dialog, Action properties dialog will be opened on clicking the OK button.
There are two more options to choose where the call for the copied action to be inserted.
  After the current step - Call to the copied action will be created after the current step in the current action. So while executing the test, copied Action will execute after current step.
  At the end of the test - Call to the copied action will bve created at the end of the test. So copied action will be executed after the execution of all the existing action.



Call to Existing Action...:
   This option will just create a call to the existing action without copying it. If the original action is modified, it will affect all the places where the action is called. When selecting the 'Call to Existing Action..' option, "Select Action" dialog will be opened. By default, all the actions associated with the current test will be listed.
   If you are creating a call to an Action from another test, it will be called as "External Actions". Actually, these External actions are read-only in the calling test. But you can use the local editable copy of data table for these external actions.

Thursday, May 17, 2012

:: LoadAndRunAction ::


    LoadAndRunAction is the new feature in QTP that indroduced in the version 10.0. This method is used to load the action dynamically during run time.


   In the above picture, you are seeing that we can insert call to an existing Action. Actually, it will create links to the corresponding action before we start executing the script. You may have 100 Actions already mapped or linked to the driver script. But you going to run only the 10 actions. In that case, the remaining 90 actions will be loaded before the execution but actually those actions will not be executed. So,What If you want to load the action based on your need?
Here is the way to Load actions during run time. LoadAndRunAction method is used to load only the required action during run time. This will help you to save more time when you have more number of actions and you want to execute only few out of it.

How to Use:
    Syntax:  LoadAndRunAction "Test Name with path", "Action Name"
          Ex:  LoadAndRunAction "C:\Automation Scripts\Test1","Action1"

LoadAndRunAction load any reusable external action from another test during run time.

Monday, April 16, 2012

Environment Variables in QTP


        Environment variables are similar to Global variables to store values. Environment variables can be accessed at any place in the script and the values will be the same. Also, we can modify the values at any place and the modified values will be retrieved on further use.
Environment variables are very useful when we want to share a variable across actions in a test.
There are two types of Environment variables.
1. Built-In
2. User Defined

1. Built-In:
     There are some predefined Environment variables provided by QTP. We can use these environment variables without having assigned any values manually. Built-In environment variables contains values such as test path, OS version, Current Action,Current Action Iteration, User name etc.,

For Ex: If you want to get the path where the test is saved then you can use "TestDir" Environment variable.

How to Read environment variable from QTP Script?
Syntax: Environment.value("Variable Name")
Msgbox Environment.value("OS")

This will print the Operating System of the machine on which QTP is installed.

Below are some other Built-In Environment Varaibles:
1. Action Iteration: Indicates which action iteration is currently running. The value will be displayed or valid only during the test run.
2. Action Name: Displays or indicates which action is currently running. The current value is valid only during test run.
3. ControllerHostName: The name of the computer that serves as the controller. Used when Load runner is running. The current value is valid only during test run under Load.
4. GroupName: This is w.r.t. Load Runner. It is the scenario identification number. The current value is valid only during test run under Load.
5. LocalHostname: Gives the Local Host Name on which QTP is Installed. The current value displayed is WINDOWS XP.
6. OS: Displays the operating system on which QTP is installed. The current value os Microsoft Windows XP Work Station.
7. OS Version: Displays the version of the Operating System.
8. ProductDir: Displays the folder path where the product (QTP) is installed.
9. ProductName: Gives the name of the Product.
10. ProductVersion: Gives the product version.
11. ResultDir: Displays the folder path where the current test results are saved.
12. SceanrioId: This is w.r.t. LoadRunner. Displays the scenario identification number.
13. SystemTempDir: Displays the system temporary directory.
14. TestDir: This is the path of the folder in which the test is located.
15. TestIteration: Indicates which test iteration is currently running.
16. TestName: Displays the name of the test.
17. UpdatingActiveScreen: Indicates whether the active screen images and values are being updated.
18. UpdatingCheckPoints: Indicates whether the checkpoint properties are being updated.
19. UpdatingToDescriptions: Indicates whether test object descriptions are being updated.
20. UserName: Displays the windows login user name.
21. VUserId: This is w.r.t. Load Runner. Indicates the virtual user identification number.


2. User Defined
     These are all the environment variables defined by the user. User can store the run time values or any other own values for further access in the script.
     There are two types to User Defined Environment variables.
      a. Internal
      b. External
a. Internal:
     Internal Environment variables are the one created by the user with in the test. These variables can be used only with in the test in which it is created. Internal environment variables can be created in two ways.
   Method 1:
         1. Go to File->setting->environment tab. 
         2. Select variable type as User defined
         3. Click on “+” sign.
         4. Add name for e.g qtp
         5. Add value for e.g. http://testeverything-qtp.blogspot.com
         Click on apply and ok. 

  Method 2:
  Environment.value("<variable name>") = <Value>
  Environment.value("qtp") = "http://testeverything-qtp.blogspot.com"

These Environment variables also can be accessed as below
Msgbox Environment.value("qtp")
"http://testeverything-qtp.blogspot.com"  will be displayed in the msgbox.

b. External:
External environment variables that you pre-defined in the active external
environment variables file.These external file contains the name & value pair in XML format. You can create as many files as you want and select an appropriate file for each test. Note that external environment 

variable values are designated as read-only within the test.

To create an external environment variables file:
 1 Open any text editor.
 2 Type [Environment] on the first line.
 3 Type one variable-value pair on each line in the format—variable=value.
 4 Save the file in a location that is accessible from the QuickTest machine. The 
file must be a text file, but you can use any file name extension (usually, it will be saved in XML Format).
For example:
[Environment]
MyParam1=10
MyParam2=20
MyParam3=http://testeverything-qtp.blogspot.com

To select the active external environment-variables file:
 1 Choose Test > Settings to open the Test Settings dialog box.
 2 Click the Environment tab.
 3 Select the Load variables and values from external file (reloaded each test run) check box.
 4 Use the browse button or enter the full path of the external environment-variables file you want to use with your test.


Friday, March 30, 2012

FTP - File Operations

Great to see you all back! Below is the script to connect, read files from FTP (File Transfer Protocal) location.



 'Script to Check If file exists in FTP

 Extern.Declare micLong, "InternetOpen", "Wininet.dll", "InternetOpenA", micString, micDWord, micString, micString, micDWord
 Extern.Declare micLong, "InternetConnect", "Wininet.dll", "InternetConnectA", micLong, micString, micInteger, micString, micString, micDWord, micDWord, micDWord
 Extern.Declare micInteger, "FtpGetFile","Wininet.dll","FtpGetFileA", micLong, micString, micString, micInteger, micDWord, micDWord, micDWord
 Extern.Declare micInteger, "FtpFindFirstFile", "wininet.dll", "FtpFindFirstFileA", micLong, micString,miclong, micDWord
 Extern.Declare micInteger, "InternetCloseHandle", "wininet.dll", "InternetCloseHandle", micLong
 Dim WIN32_FIND_DATA,INTERNET_FLAG_NO_CACHE_WRITE
 ' constants declaration

 Const INTERNET_OPEN_TYPE_DIRECT = 1
 Const INTERNET_DEFAULT_FTP_PORT = 21
 Const INTERNET_SERVICE_FTP = 1
 Const FTP_TRANSFER_TYPE_ASCII = 1
 Const FTP_TRANSFER_TYPE_UNKNOWN = 0
 Const FTP_TRANSFER_TYPE_BINARY = 2
 'Variable declaration

 FTP_FILE_PATH = <FTP File path>
 FTP_FileName = <FTP File name>
 FTP_USERID = <User ID to connect FTP>
 FTP_PASSWORD = <Password to connect FTP>
 ' To FTP the specified interface file.

 objInternet = Extern.InternetOpen("QTP_FTP", INTERNET_OPEN_TYPE_DIRECT, vbNullChar, vbNullChar, 0)
 If objInternet = 0 Then
 Reporter.ReportEvent micFail, "InternetOpen", "InternetOpen: Failed to setup environment."
 'ExitTest
 End If
 objConnect = Extern.InternetConnect(objInternet, FTP_SERVER , INTERNET_DEFAULT_FTP_PORT, FTP_USERID , FTP_PASSWORD, INTERNET_SERVICE_FTP, 0, 0)
 If objConnect = 0 Then
 Reporter.ReportEvent micFail, "InternetConnect", "InternetConnect: Failed to open internet connection."
 'ExitTest
 End If
 RemoteLocation =FTP_FILE_PATH & "/" & FTP_FileName
 'Verify file exists in FTP Directory

 bRetval =Extern.FtpFindFirstFile(objConnect,RemoteLocation,WIN32_FIND_DATA, INTERNET_FLAG_NO_CACHE_WRITE)
 bRetval=left(bRetval,2)
 If bRetVal=0 Then
  Reporter.ReportEvent micFail, "File Not Found ", "File " & RemoteLocation  & "Not found "
 Else
  Reporter.ReportEvent micPass, "File Found ", "'" & RemoteLocation & "' File found"
 End If
 Extern.InternetCloseHandle(objConnect)
 Extern.InternetCloseHandle(objInternet)
'==============================================================
 'Script to Download file from FTP
'Note : In this example, File will be downloaded to "C:\Local_Index.txt"

 Extern.Declare micLong, "InternetOpen", "Wininet.dll", "InternetOpenA", micString, micDWord, micString, micString, micDWord
 Extern.Declare micLong, "InternetConnect", "Wininet.dll", "InternetConnectA", micLong, micString, micInteger, micString, micString, micDWord, micDWord, micDWord
 Extern.Declare micInteger, "FtpGetFile","Wininet.dll","FtpGetFileA", micLong, micString, micString, micInteger, micDWord, micDWord, micDWord
 Extern.Declare micInteger, "FtpFindFirstFile", "wininet.dll", "FtpFindFirstFileA", micLong, micString,miclong, micDWord
 Extern.Declare micInteger, "InternetCloseHandle", "wininet.dll", "InternetCloseHandle", micLong
 Dim WIN32_FIND_DATA,INTERNET_FLAG_NO_CACHE_WRITE
 ' constants declaration

 Const INTERNET_OPEN_TYPE_DIRECT = 1
 Const INTERNET_DEFAULT_FTP_PORT = 21
 Const INTERNET_SERVICE_FTP = 1
 Const FTP_TRANSFER_TYPE_ASCII = 1
 Const FTP_TRANSFER_TYPE_UNKNOWN = 0
 Const FTP_TRANSFER_TYPE_BINARY = 2
 'Variable declaration

 FTP_FILE_PATH = <FTP File path>
 FTP_FileName = <FTP File name>
 FTP_USERID = <User ID to connect FTP>
 FTP_PASSWORD = <Password to connect FTP>
 ' To FTP the specified interface file.

 objInternet = Extern.InternetOpen("QTP_FTP", INTERNET_OPEN_TYPE_DIRECT, vbNullChar, vbNullChar, 0)
 If objInternet = 0 Then
 Reporter.ReportEvent micFail, "InternetOpen", "InternetOpen: Failed to setup environment."
 'ExitTest
 End If
 objConnect = Extern.InternetConnect(objInternet, FTP_SERVER , INTERNET_DEFAULT_FTP_PORT, FTP_USERID , FTP_PASSWORD, INTERNET_SERVICE_FTP, 0, 0)
 If objConnect = 0 Then
 Reporter.ReportEvent micFail, "InternetConnect", "InternetConnect: Failed to open internet connection."
 'ExitTest
 End If
 RemoteLocation =FTP_FILE_PATH & "/" & FTP_FileName
 'DownLoad File

 bRetval = Extern.FtpGetFile( objConnect, RemoteLocation, "C:\Local_Index.txt", 0, 0, FTP_TRANSFER_TYPE_ASCII, 0 )
 If Not CBool ( bRetVal ) Then
    Reporter.ReportEvent micFail, "FtpGetFile", "Failed to open download file."
 Else
    Reporter.ReportEvent micPass, "FtpGetFile", "File Downloaded Successfully : "& bRetval
 End If
 Extern.InternetCloseHandle(objConnect)
 Extern.InternetCloseHandle(objInternet)

Monday, March 26, 2012

SendKeys method in QTP


     SendKeys is a method used to perform keystroke events on any opened application. Some times QTP may not identify specific objects and Sendkeys can be used in those situations to perform those operations if that can be done with Key strokes. SendKeys is the method of "WScript.Shell" class.

Here is the example of Sending key value "A" to the application
Set WshShell = CreateObject("WScript.Shell")
WshShell.SendKeys "{A}"
Set WshShell = Nothing 

We can also use Sendkeys for the operations that involves multiple keystrokes. Say for Instance, If we want our script to close any opened window (using ALT+F4 or ALT+F and X), we can use the below script. 

Set WshShell = CreateObject("WScript.Shell")
WshShell.SendKeys "%f"
wait 3
WshShell.SendKeys "x"
wait 3
Set WshShell = Nothing
++++++++++++++++++++++++++++++
OR
++++++++++++++++++++++++++++++
Set WshShell = CreateObject("WScript.Shell")
 wait 2
WshShell.SendKeys "%{F4}"
wait 3
Set WshShell = Nothing


Here % is the symbol to send ALT key. For the shift key it is "+" and for the CTRL key it is "^".

In following table you will find all keys and their argument that you may need.


Name of Key
Argument
BACKSPACE
{BACKSPACE}, {BS}, or {BKSP}
BREAK
{BREAK}
CAPS LOCK {CAPSLOCK}
{CAPSLOCK}
DEL or DELETE
{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}
Y 10 times
{Y 10}
Space
" "
plus sign      
 "+"
caret            
"^"
percent sign
"%"
tilde      
"~"



Sunday, January 22, 2012

Components & Different Views in QTP

Components of QTP




Different views in QTP
•Keyword view & Expert View – Used to generate script.
•Information Pane - The Information pane lists the syntax errors found in your document, and enables you to locate each syntax error so that you can correct it.
•Active Screen - The Active Screen provides a snapshot of your application as it appeared when you performed the corresponding step during a recording session.
•Missing Resource - The Missing Resources pane provides a list of the resources that are specified in your test but cannot be found. Missing resources can include calls to missing actions, missing function libraries, missing recovery scenarios, missing environment variable XML files, unmapped shared object repositories, and parameters that are connected to shared object repositories.


•Debug Viewer - The Debug Viewer pane assists you in debugging your tests or function libraries.
       •This pane contains three tabs—Watch, Variables, and Command.


•Data table - The Data Table contains one Global tab plus an additional tab for each action in your test. The Data Table assists you in parameterizing your test. To view the Data Table, click the Data Table toolbar button or select View >Data Table.


Link to Similar Posts



Environments Supported by QTP


Environments Supported by QTP:

QuickTest Professional supports functional testing of all enterprise environments, including
Windows,
Web,
.NET,
Java/J2EE,
SAP,
Siebel,
Oracle,
PeopleSoft,
 Visual Basic,
 ActiveX,
 mainframe terminal emulators, and more..

Thursday, January 19, 2012

ZIP & UNZIP files in QTP

'=======================================================
'ZIP:
'=======================================================
Function WindowsZip(sFile, sZipFile)
     Set oZipShell = CreateObject(“WScript.Shell”)
     Set oZipFSO = CreateObject(“Scripting.FileSystemObject”)

     If Not oZipFSO.FileExists(sZipFile) Then
       NewZip(sZipFile)
     End If

     Set oZipApp = CreateObject(“Shell.Application”)
     sZipFileCount = oZipApp.NameSpace(sZipFile).items.Count
     aFileName = Split(sFile, “\”)
     sFileName = (aFileName(Ubound(aFileName)))
    REM  listfiles

     sDupe = False

     For Each sFileNameInZip In oZipApp.NameSpace(sZipFile).items
        If LCase(sFileName) = LCase(sFileNameInZip) Then
         sDupe = True
         Exit For
       End If
    Next

     If Not sDupe Then
     oZipApp.NameSpace(sZipFile).Copyhere sFile
     REM  Keep script waiting until Compressing is done
     On Error Resume Next
      sLoop = 0
      Do Until sZipFileCount < oZipApp.NameSpace(sZipFile).Items.Count
         Wscript.Sleep(100)
         sLoop = sLoop + 1
       Loop
    On Error GoTo 0
     End If
  End Function
'=======================================================
'UnZip:
'=======================================================
Function Unzip(strFilePath, strFileName, blnOverWriteFiles, blnDeleteZipFileAfterExtract, out_ExtractToFolder)
' This routine unzips a file. NOTE: The files are extracted to a folder '
' in the same location using the name of the file minus the extension.  '
' EX. C:\Test.zip will be extracted to C:\Test ' 'strFile (String) = Full path and filename of the file to be unzipped. '
  Dim arrFile
  Dim FileInsideZip, FilesInsideZip
  Dim fso, strFile, pathToZipFile, extractTo
  Dim objShell

  Unzip = ""
  strFile = strFilePath & "\" & strFileName
  arrFile = Split(strFile, ".")
  Set fso = CreateObject("Scripting.FileSystemObject")
  If Not fnVerifyFileExists(strFilePath, strFileName) Then
   Reporter.ReportEvent micFail, "Unzip file : " & strFilePath & "\" & strFileName, "File does not exist"
   Exit Function
  End If
  fnCreateFolderStructure arrFile(0)    'Build the folder tree
 ' fso.CreateFolder(arrFile(0) & "\ ")
  pathToZipFile= arrFile(0) & ".zip"
  extractTo= arrFile(0) '& "\"
  Set objShell = CreateObject("Shell.Application")
  Set filesInzip=objShell.NameSpace(pathToZipFile).items

  'Verify that if files present in the zip file is already present in the folder. If yes, then delete those.

   For each itm in objShell.NameSpace(pathToZipFile).items
    FileInsideZip = itm.Name
      If  FilesInsideZip = "" Then
       FilesInsideZip = FileInsideZip
      Else
       FilesInsideZip = FilesInsideZip & ";" & FileInsideZip
      End If
    If blnOverWriteFiles = True Then
     If fnVerifyFileExists (extractTo, FileInsideZip) = True Then
      fnDeleteFile ExtractTo, FileInsideZip
     End If
    End If
   Next
  objShell.NameSpace(extractTo).CopyHere filesInzip

  If blnDeleteZipFile = True Then
   fso.DeleteFile pathToZipFile, True
  End If
  Reporter.ReportEvent micDone, "Unzip File : " &  strFilePath & "\" & strFileName, "Unzipped location : " & extractTo & vbcrlf & vbcrlf & "Files Unzipped : " & vbcrlf & FilesInsideZip
  Unzip = FilesInsideZip
  out_ExtractToFolder = extractTo
  Set fso = Nothing
  Set objShell = Nothing
End Function 'Unzip
'=======================================================
'Verify File Exists in the Specified Directory
Function fnVerifyFileExists(FilePath, FileName)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fnVerifyFileExists = fso.FileExists(FilePath & "\" & FileName)
   Set fso = Nothing
End Function
'=======================================================
'Delete the specified File
Function fnDeleteFile(strFilePath, strFileName)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   If  fso.FileExists(strFilePath & "\" & strFileName) Then
    fso.DeleteFile strFilePath & "\" & strFileName
 End If
 Set fso = Nothing
End Function
'=======================================================
'Creates the entire folder structure
Function fnCreateFolderStructure(FolPath)
   Dim fso, arrFolderPath
   Dim fIndex,i, CurrentFolderPath
   Set fso = CreateObject("Scripting.FileSystemObject")
   arrFolderPath = Split(FolPath, "\")
 For fIndex = 0 to Ubound(arrFolderPath)     '0 will always have Drive letter
  CurrentFolderPath = 0
  For i = 0 to fIndex
   If i = 0 Then
    CurrentFolderPath = arrFolderPath(i)
   Else
    CurrentFolderPath  = CurrentFolderPath & "\" & arrFolderPath(i)
     End If
  Next

  If Not fso.FolderExists(CurrentFolderPath)  Then
   fso.CreateFolder CurrentFolderPath
  End If

   Next
   Set fso = Nothing
End Function

Functions to work with QC Attachments


'===============================================================
'Description : Returns the path of downloaded attachment
'===============================================================
'Example Usage :
' If you want to move the downloaded file to c:\ folder
' attpath = DownloadAttachment(“attachmentname”,”Root\D2D\Purchasing”, “TRUE”)
' If you DO NOT want to move the downloaded file to c:\ folder
' attpath = DownloadAttachment(“attachmentname”,”Root\D2D\Purchasing”, “FALSE”)

Public Function DownloadAttachment(TDAttachmentName, TDFolderPath, bMovetoRoot)
 Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
 Dim otaAttachment 'As TDAPIOLELib.Attachment
 Dim otaAttachmentList 'As TDAPIOLELib.List
 Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
 Dim otaTreeManager 'As TDAPIOLELib.TreeManager
 Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
 Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
 Dim fso
 Dim strPath 'As String

 Set fso = CreateObject("Scripting.FileSystemObject")
 Set otaTreeManager = QCUtil.TDConnection.TreeManager
 Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
 Set otaAttachmentFactory = otaSysTreeNode.Attachments
 Set otaAttachmentFilter = otaAttachmentFactory.Filter
 otaAttachmentFilter.Filter("CR_REFERENCE") = "'ALL_LISTS_" & otaSysTreeNode.NodeID & "_" & TDAttachmentName & "'"
 Set otaAttachmentList = otaAttachmentFilter.NewList
 If otaAttachmentList.Count > 0 Then
  set otaAttachment = otaAttachmentList.Item(1)
  otaAttachment.Load True, ""
  strPath = otaAttachment.FileName
        If (bMovetoRoot) Then
   If (fso.FileExists(otaAttachment.FileName)) Then
    fso.CopyFile strPath, "c:\" & TDAttachmentName
    DownloadAttachment = "c:\" & TDAttachmentName
   Else
    DownloadAttachment = strPath
   End if
  Else
   DownloadAttachment = strPath
  End if
 Else
  fnReportEvent micFail, "Failure in library function 'GetFolderAttachmentPath'", "Failed to find attachment '" & TDAttachmentName & "' in folder '" & TDFolderPath & "'."
  DowloadAttachment = "Empty"
 End If
 Set otaAttachmentFactory = Nothing
 Set otaAttachment = Nothing
 Set otaAttachmentList = Nothing
 Set otaAttachmentFilter = Nothing
 Set otaTreeManager = Nothing
 Set otaSysTreeNode = Nothing
 Set fso = Nothing
End Function
'===============================================================
'Upload a File to QC to a specific path
'===============================================================
Public Function UploadAttachment(TDFolderPath,sFilePath)
 Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
 Dim otaAttachment 'As TDAPIOLELib.Attachment
 Dim otaAttachmentList 'As TDAPIOLELib.List
 Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
 Dim otaTreeManager 'As TDAPIOLELib.TreeManager
 Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
 Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
 Dim fso
 Dim strPath 'As String

 Set fso = CreateObject("Scripting.FileSystemObject")
 Set otaTreeManager = QCUtil.TDConnection.TreeManager
 Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
 Set otaAttachmentFactory = otaSysTreeNode.Attachments
 Set ObjAttch = otaAttachmentFactory.AddItem(Null)
 ObjAttch.FileName = sFilePath
 ObjAttch.Type = 1
 ObjAttch.Post
 ObjAttch.Refresh

 Set otaAttachmentFactory = Nothing
 Set otaAttachment = Nothing
 Set otaAttachmentList = Nothing
 Set otaAttachmentFilter = Nothing
 Set otaTreeManager = Nothing
 Set otaSysTreeNode = Nothing
 Set fso = Nothing
End Function
'===============================================================
'Delete a QC Attachment file
'===============================================================
Public Sub DeleteFolderAttachment(TDAttachmentName, TDFolderPath)
'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaTreeManager 'As TDAPIOLELib.TreeManager
Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
Dim strPath 'As String
Set otaTreeManager = QCUtil.TDConnection.TreeManager
Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
Set otaAttachmentFactory = otaSysTreeNode.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
otaAttachmentFilter.Filter("CR_REFERENCE") = "'ALL_LISTS_" & otaSysTreeNode.NodeID & "_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count > 0 Then
otaAttachmentFactory.RemoveItem otaAttachmentList.Item(1).ID
Else
Reporter.ReportEvent micFail, "Failure in library function 'GetFolderAttachmentPath'", "Failed to find attachment '" & TDAttachmentName & "' in folder '" & TDFolderPath & "'."
End If