Create a new Excel Sheet

Dim ExcelSheet Set ExcelSheet = CreateObject("Excel.Sheet") Excelsheet.SaveAs "C:\Automation\TEST.XLS"

Open a folder SystemUtil.Run "C:\Documents and Settings\x108536\Start Menu\Programs" Can use SystemUtil for wide varity of functions.

To return a value from a function, assign the value to the function name.    Function ReportFolderStatus(fldr)    Dim fso, msg    Set fso = CreateObject("Scripting.FileSystemObject")    If (fso.FolderExists(fldr)) Then       msg = fldr & " exists."    Else       msg = fldr & " doesn't exist."    End If    ReportFolderStatus = msg End Function (This checks whet the folder exists) Datatable import and running: datatable.Import("C:\Documents and Settings\x108536\Desktop\mahesh.xls") For i=0 to 2 Browser("Desktop One").Page("Desktop  One").Frame("searchAreaIFrame").WebEdit("accountNumber").Set DataTable("p_Text") Browser("Desktop One").Page("Desktop One").Frame("searchAreaIFrame").Link("Search").Click Browser("Desktop One").Page("Desktop One").Frame("cid0_billingAccountsIFrame").WebElement("13135  64 S...").Click Browser("Desktop One").Page("Desktop One").Sync Browser("Desktop One").Page("Desktop One").WebElement("WebElement").Click datatable.SetNextRow next

1. When working with tests, you can also measure how long it takes certain parts of your test to run,  using transaction statements.

2. ** Inserting Steps Using the Step Generator**
To open the Step Generator from the Keyword View or Expert View: 1. While recording or editing, click the step which you want the new step to follow. (When you finish defining the new step, QuickTest will insert it after this step.) 2. Choose Insert > Step > Step Generator or right-click the step and choose Insert Step > Step Generator. Alternatively, press F7.

3.

Fixing scripts where property changes very often ( Dynamic Changing)

There are several methods for modifying test object properties. Choose the method that best fits your needs:
• •

You can manually change a test object property value to match a new static property of an object in your application. You can use the SetTOProperty method to modify test object properties during a run session without changing the property values in the object repository. You can modify the set of properties that QuickTest uses to identify the object, so that it will be able to identify an object even when some of its properties change. You can parameterize a test object property with a Data Table parameter if you expect the property value to change in a predictable way with each iteration of the test. You can use regular expressions to identify an object based on conditions or patterns you define.

4.

To specify a variable to store an object, use the Set statement, with the following syntax: Set ObjectVar = ObjectHierarchy

5. You can use VB script to generate all the setting of QTP, use it for all your QTP scripts (Same  setting ) there is an generate option or you can write your own vbscript to open QTP and load your  settings

6.

The GetTOProperty and GetTOProperties methods enable you to retrieve a specific property value or all the properties and values that QuickTest uses to identify an object. The SetTOProperty method enables you to modify a property value that QuickTest uses to identify an object.

For example, the following statements would set the Submit button's name value to my button, and then retrieve the value my button to the ButtonName variable: Browser("QA Home Page").Page("QA Home Page").WebButton("Submit").SetTOProperty "Name", "my button" ButtonName=Browser("QA Home Page").Page("QA Home Page").WebButton("Submit").GetTOProperty("Name")
7.

Description Vertically scrolls an object that has embedded scrollbars. Syntax object.VScroll iOption, [Item] Browser("Mercury Quality Center").Page("Mercury Quality Center").ActiveX("Loader Class v2").WinObject("TTDApiGrid").VScroll micLineNext,21

8.

Description Moves the scroll bar upward, or to the left, the specified number of lines. Syntax object.PrevLine [Item]
9.

Description Returns the value of the specified property from the test object description. Remarks This method is common to all standard Windows test objects. For additional information and examples of usage, see GetTOProperty.
10.

Description Returns the current value of the test object property from the object in the application. Remarks This method is common to all standard Windows test objects. For additional information and examples of usage, see GetROProperty.

11. value=Browser("Desktop One").Page("Desktop  One").Frame("cid0_createCustomerAreaIFrame_2").webElement("Service(s)  Unavailable").GetROProperty("outerhtml")

12. Parametrising Links 'var = Browser("TELUS | Personal | Your").Page("TELUS | Personal |  Your_2").link(DataTable("Link", dtGlobalSheet)).Exist 13. Running a excel macro: set obj = CreateObject("Excel.Application") obj.Workbooks.Open "C:\\macrotry.xls" ' Call the run command to execute a macro or function in Excel obj.Run "Sample" obj.ActiveWorkbook.save obj.Quit set obj = Nothing

Another alternative is to use the Visible property to bring up the actual Excel UI, then use Low Level Recording to press the control keyboard sequence that has been specified to start the macro. For the following example, CTRL-L has been specified as the control sequence to start the macro that was used. Low Level Recording was used to record this operation. Example 2: set obj = CreateObject("Excel.Application") obj.Workbooks.Open "C:\\macrotry.xls" ' Make the Excel UI visible obj.Visible = TRUE ' Using Low Level Recording, activate the window and press the keyboard ' sequence you have specified for the macro. In this example, we used ' the keyboard sequence Ctrl-L to activate the macro Window("macrotry.xls").Activate Window("macrotry.xls").WinObject("macrotry.xls").Type micCtrlDwn + "l" + micCtrlUp obj.ActiveWorkbook.save obj.Quit set obj = Nothing

14. get data from an Excel file without importing the data to the data table

GetValueInFile (sfilePath, isheet, irow, icolumn) sfilePath isheet irow icolumn The path and name of the excel file. The sheet of the excel file. This can be an index number or the sheet name. The row number in the table. The column number in the table.

Function GetValueInFile (sfilePath, isheet, irow, icolumn) Set ExcelObj = CreateObject("Excel.Application") ExcelObj.Workbooks.Open sfilePath Set NewSheet = ExcelObj.Sheets.Item(isheet) value = NewSheet.Cells(irow,icolumn) ' ExcelObj.ActiveWorkbook.Save ExcelObj.Application.Quit Set ExcelObj = Nothing GetValueInFile = value End Function Example: dim filename filename = "D:\temp\Test.xls" msgbox GetValueInFile(filename,1,2,2) msgbox GetValueInFile(filename,"Sheet1",1,1) msgbox GetValueInFile(filename,2,2,2) msgbox GetValueInFile(filename,3,1,1)
15 Stop Test Execution: To stop test execution from within a test script, you can use the ExitAction or ExitTest statements. The  ExitAction statement will stop execution of the current action. If additional actions follow within the test,  execution will continue with them. ExitTest ends the test execution completely. 16 PostMessage to send a virtual key to the application

Example: ' Define constants for use with PostMessage Const WM_CHAR = 258 Const WM_KEYDOWN = 256 Const VK_F7 = 118 Const VK_F13 = 124 Const WM_KEYUP = 257 ' Declare PostMessage for use Extern.Declare micLResult , "PostMessage", "user32.dll", "PostMessage", micHwnd, micUInteger ,  micWParam, micLParam  ' Get the handle for the window Window("Name").Activate hWnd = Window("Name").GetROProperty("hwnd") ' Press the F7 keyboard key Extern.PostMessage hWnd, WM_KEYDOWN, VK_F7, 0 Extern.PostMessage hWnd, WM_KEYUP, 0, 0

17 How to send a key command to a Web object

1. Download and install the Windows Scripting Host, if you do not already have it. 2. Create a WScript.Shell object. 3. Activate the browser in which you want to execute the keys. 4. Use the SendKeys method to type the key combination. Example: ' This code executes the CTRL+F key combination (search) on a browser. Set WshShell = CreateObject("WScript.Shell") WshShell.AppActivate "Put the label of the browser" ' Activate the browser window wait(3) WshShell.SendKeys "^f" ' The caret (^) represents the CTRL key. wait(2) object.SendKeys(string) object A WshShell object. string The string value indicating the keystroke(s) you want to send.

The SendKeys method will send keystroke(s) to the active window. To send a single character (for example, x), use "x" as the string argument. To send multiple characters (for example, abc), use "abc" as the string argument. You can also send special characters such as SHIFT, CTRL, and ALT, which are represented by the plus sign (+), the caret (^), and the percent sign (%), respectively.
b. ' Declare the function  Extern.Declare micInteger,"keybd_type", "C:\temp\csolib2.dll", "keybd_type", micString ' Put focus in the WebEdit object Browser("Yahoo! Mail ­ The best_2").Page("Yahoo! Mail ­ The best").WebEdit("login").Click 5,5 ' Use the keybd_type function to enter the specified keystrokes. Extern.keybd_type("j")

18 Property values of objects in your application may change dynamically each time your application opens, or  based on certain conditions. To make the test object property values match the property values of the run­ time object, you can modify test object properties manually while designing your test or component or  using SetTOProperty statements during a run session. You can also use regular expressions to identify  property values based on conditions or patterns you define, or you can parameterize property values with  Data Table parameters so that a different value is used during each iteration of the test (this option is not  applicable to components). 19 How to enable or disable error/warning messages in test results ( at particular points)

Capturing the return value or the results of a statement in the script does not prevent QuickTest Professional from writing a message to the test results. To control the messages that are written to the test results, you need to enable or disable the Reporter.Filter property as needed within the script. The Reporter.Filter property retrieves or sets the current mode for displaying events in the test results. You can use this method to completely disable or enable reporting of steps following the statement, or you can indicate that you only want subsequent failed or failed and warning steps to be included in the report. To retrieve the mode setting: CurrentMode = Reporter.Filter To set the mode: Reporter.Filter = NewMode

The mode can be one of the following values: 0 or rfEnableAll 1 or rfEnableErrorsAndWarnings 2 or rfEnableErrorsOnly 3 or rfDisableAll Example: ' Capture the current filter value CurrentMode = Reporter.Filter ' Disable all error and warning messages Reporter.Filter = rfDisableAll ' Execute the checkpoint result = Dialog("Login").WinEdit("Agent Name:").Check(CheckPoint("Agent Name:")) Reporter.ReportEvent micDone, "General message", "This general message should not appear in the test results" Reporter.ReportEvent micPass, "Pass message", "This pass message should not appear in the test results" Reporter.ReportEvent micFail, "Fail message", "This fail message should not appear in the test results" ' Reset the filter value Reporter.Filter = CurrentMode Reporter.ReportEvent micDone, "Checkpoint results", "the results were: " & result All reported events are displayed in the test results. (Default) Only event with a warning or fail status are displayed in the test results. Only events with a fail status are displayed in the test results. No events are displayed in the test results.

20.

QuickTest identifies a virtual object according to its boundaries. Marking an object's boundaries specifies its size and position on a Web page or application window. When you assign a test object as the parent of your virtual object, you specify that the coordinates of the virtual object boundaries are relative to that parent object. When you record a test or component, QuickTest recognizes the virtual object within the parent object and adds it as a test object in the object repository so that QuickTest can identify the object during the run session.

Note: The Web page or application window must be the same size and in the same position when recording and running tests or components as it was when you defined the virtual object. You can disable recognition of virtual objects without deleting them from the Virtual Object Manager. For additional information, see Removing or Disabling Virtual Object Definitions. Notes: You can use virtual objects only when recording and running a test or component. You cannot insert any type of checkpoint on a virtual object, or use the Object Spy to view its properties. In order to perform an operation in the Active Screen on a marked virtual object, you must first record it, so that its properties are saved in the test object description in the object repository. If you perform an operation in the Active Screen on a virtual object that has not yet been recorded, QuickTest treats it as a standard object.
21 Systemutil.run “notepad” 22 QuickTest Professional is unable to record on icons located in the system tray

QuickTest Professional (QTP) does not generate any code while recording right-clicking on an icon in the system tray and selecting an item from the pop-up menu. Diagnosis: By default, QuickTest Professional does not record on the system tray and pop-up menu's like the one seen for MS Messenger and similar programs. The reason why QTP does not record on the pop-up menu items is that the menu's parent window is not visible. By default, QTP records a command if the object and all its parents are visible. In order to enable recording on an object with an invisible parent, the parent must have the "visible" property as one of the mandatory properties.

Solution: Set the "visible" property to mandatory for the Window object to record on the icon`s popup menu A two step process is involved in order to select an item from a system tray icon's pop-up menu; open the pop-up menu and select the item from the pop-up menu. The code to open the pop-up menu (i.e., the right-click on the icon) needs to manually entered. The code to select an menu item from the pop-up menu can be recorded, but you will need to modify the Object Identification Settings for the Windows objects (Window and WinObject in this case) first.

1. Add the "visible" property to the mandatory list for the Window and WinObject objects. For information on modifying the mandatory properties, refer to Problem ID 30733 - How to modify the recorded properties of an object or window. Once the "visible" property has been added, QuickTest Professional should record selecting the item from the pop-up menu. This modification will not make QuickTest Professional record the right click on the system tray icon. 2. Manually add the code to open the pop-up menu to your script: a. Switch to Expert View. b. Copy the following line into the QuickTest Professional script where you wish to click on the system tray icon: Window("regexpwndclass:=Shell_TrayWnd").WinObject("regexpwndclass:=Tray NotifyWnd").WinToolbar("nativeclass:=ToolbarWindow32").Press "<item name>", micRightBtn c. Modify the arguments to the Press method (above) as needed: o The first argument needs to match the icon name in the system tray that needs to be selected. The icon name is seen when the mouse is moved over the icon. Note that the name is case sensitive. o If you need to left-click on the icon, then use micLeftBtn as the second argument in the Press method. 3. Record selecting the desired menu item from the pop-up menu. QuickTest Professional should record a line similar to the following: Window("Y!TrayWnd").WinMenu("ContextMenu").Select "Show Yahoo! Messenger" The final code (with the manually entered line and the recorded recorded menu item selection) should look similar to the following example: Example: ' Right click on the Yahoo! Messenger icon Window("regexpwndclass:=Shell_TrayWnd").WinObject("regexpwndclass:=TrayNotify Wnd").WinToolbar("nativeclass:=ToolbarWindow32").Press "Yahoo! Messenger", micRightBtn ' Select the "Show Yahoo! Messenger" menu item Window("Y!TrayWnd").WinMenu("ContextMenu").Select "Show Yahoo! Messenger" Note: The above steps should work with QTP 8.0 and above.
23

Problem Description: How to measure the time required to navigate between pages

Solution: Use transactions or time functions There are two ways to measure the time it takes to navigate between two pages or to execute a process. 1. Use the VBScript timer function. Timer The timer function takes no parameters and returns the number of seconds that have elapsed since 12:00 AM (midnight). This method will not run overnight. Example: a = Timer 'Starting time (in seconds from midnight) ' additional code would go here b = Timer ' Ending time (in seconds from midnight) ' Calculate the time the actions took to execute. c = b-a Note: You should enter the Timer function code into your script from the Expert View. This time will be returned in seconds. If you need the time in milliseconds, multiply the calculated value by 1000. Example: a = Timer 'Starting time (in seconds from midnight) ' additional code would go here b = Timer ' Ending time (in seconds from midnight) ' Calculate the time the actions took to execute. c = (b-a) * 1000 msgbox c & " milliseconds" Once you have the calculated the elapsed time you can report the results to the test results by using Reporter.ReportEvent method. For more information, please refer to Problem ID 13722 - How to send pass or fail messages to the test results

2. Use the built in start/end transaction functions. Services.StartTransaction(Name) Services.EndTransaction(Name [, Status]) Name - The name of the transaction. Status - A constant or number that specifies the ending status of a transaction. Pass (0) - default Fail (1) To insert the start/end transaction points: 1. In the test tree or in Expert view, select the location where you want to insert the transaction step. 2. Go to Insert -> Start Transaction (or End Transaction). 3. Enter (or select) the transaction name. 4. Select the appropriate radio button to have the step entered into the script in the desired location. 5. Click <OK>. Example: Browser("Welcome to MSN.com").Page("Welcome to MSN.com").Sync ' Start the transaction. Services.StartTransaction "begin" Browser("Welcome to MSN.com").Navigate "http://www.google.com/" Browser("Welcome to MSN.com").Page("Google").Sync ' End the transaction. Services.EndTransaction "begin" This will allow you to measure the time to navigate to a page and the time it takes for it to be loaded. The time the transaction took to execute will be listed in the test results under the EndTransaction step. Example: "Transaction took 3.044 sec" Note: If you need to place the EndTransaction method in a different Action than its corresponding StartTransaction, you will need to do this manually in Expert View.
24

Problem Description: Can QTP record and replay against a DOS Command Prompt window Can QuickTest Professional (QTP) record and replay against a DOS Command Prompt window?

Solution: QuickTest Professional does not record against DOS windows QuickTest Professional does not record against the DOS Command Prompt window. However, it does support a replay solution. You will need to manually create the script. 1. Start recording. 2. Insert a checkpoint against the DOS window. This will add the window to the Object Repository. 3. Open the Object Repository (Tools -> Object Repository) and modify the logical name to something more meaningful if desired. 4. If the title of the window may change, remove the "regexpwndtitle" property from the learned properties list or added a regular expression to handle the dynamic portion. If you remove the title, make sure you an another property, such as index, to identify the window. 5. Manually enter the statements into the script to interact with the DOS window. Note: You can remove the checkpoint that was inserted in step 1. Example: Window("CommandPrompt").Activate Window("CommandPrompt").Type "dir" + micReturn If QuickTest Professional does not type into the DOS window, use the "wscript.shell" object instead, which contains a "SendKeys" method. Example: Set obj = CreateObject("wscript.shell") Window("CommandPrompt").Activate obj.SendKeys "dir" + chr(13) AQT/QTP does not record against 25 Connecting to Oracle database: Use OLE Database Provider or Microsoft ODBC for Oracle Driver

Below is an example on how to connect to Oracle without using a DSN connection including using the OLE DataBase Provider or using the Microsoft ODBC for Oracle driver. You may need to modify the code for use in your environment. Example: 'The code below will connect to an Oracle database, make a query, and output the field names. Dim oConn, rs Set oConn = CreateObject("ADODB.Connection") ' If you want to use OLE DB Provider, uncomment the line below 'oConn.Open "Provider=MSDAORA;server=TDORASERVER;user id=system;password=manager" ' If you want to use MS ODBC for Oracle, use the line below oConn.Open "Driver={Microsoft ODBC for Oracle};" & "Server=TDORASERVER;" & "Uid=system;" & "Pwd=manager" set rs=CreateObject("ADODB.recordset") sql = "SELECT * FROM bob_ora_db.USERS WHERE US_USERNAME='admin'" rs.Open sql, oConn for each x in rs.fields msgbox x.name

Problem Description: How to execute SQL statements in QuickTest Professional

Solution: Connect to the database and run a query To verify that information is entered into the database at runtime, you will need to add code to your script which will open a connection to the database, query the database, then close the connection. Here are the steps to do this (an example follows). 1. Create an "ADODB.Connection" object (the database object). 2. Set the connection string for the database object. 3. Open the connection to the database. 4. Execute a SQL statement. 5. Close the database connection.

The query will return the values as a tab delimited string. You can parse through the string and verify that the information is correct. Note: The exact structure of the connection string will depend on the type of database you are using. For example, if your database requires a password, you will need to include a password parameter in the connection string. For more information, refer to Problem ID 6058 - How to open a password-protected database. Example: Dim flightnumber Dim dbexample ' Create the conection object. Set dbexample = CreateObject("ADODB.Connection") ' Set the connection string and open the connection dbexample.ConnectionString = "DBQ=D:\Program Files\Mercury Interactive\WinRunner\samples\flight\app\flight32.mdb;DefaultDir=D:\Program Files\Mercury Interactive\WinRunner\samples\flight\app;Driver={Microsoft Access Driver (*.mdb)};DriverId=281;FIL=MS Access;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Thr eads=3;UserCommitSync=Yes;" dbexample.Open ' or use this method if a DSN entry was created. 'dbexample.Open("DSN=Flight32") flightnumber = 6195 ' Get the recordset returned from a select query. Set recordset = dbexample.Execute("SELECT * from Orders WHERE Flight_Number = " & flightnumber) ' Display the results of the query. msgbox recordset.GetString ' Close the database connection. dbexample.Close Set dbexample = Nothing If your query returns several columns, you can use the Fields method to retrieve data from specified columns in the returned record set. Example: ' Connect to the Flight32 database

Set dbexample = CreateObject("ADODB.Connection") dbexample.Open("DSN=Flight32") ' Perform a query Set recordset = dbexample.Execute("SELECT * from Orders") ' Get the values from the Customer_Name column while (NOT recordset.EOF) MsgBox recordset.Fields("Customer_Name") ' Move to the next value in the record set recordset.MoveNext wend ' Close the database connection. dbexample.Close Set dbexample = Nothing For more information on the Fields and MoveNext methods and working with the "ADODB.Connection" object, please refer to a VBScript reference.

32. Sometimes you need to create regular expression for the properties (even for the output value you  create)  XXX .* ­­ this is the regular expression example. 33 When you change the logical name, the logical name in the script also changes.

34.

Regular Expression:
Problem Description: How to manage a dynamic title of a browser window

Solution: Use the "CreationTime" value, a regular expression, or update the property with SetTOProperty

Option1: Reconfigure the property QuickTest Professional uses to learn the Browser. In the test's Object Repository check whether QuickTest Professional is using the "name" property to learn the browser windows. Instead of using the "name" property, reconfigure the learned properties so that QuickTest Professional uses "CreationTime" to learn the browser during recording. "CreationTime" is independent of the title of the browser and is based on when the browser was opened. This is used to differentiate each browser if you are testing in an environment that uses multiple browsers. If "name" is used with the browser window, do the following: 1. Select Tools -> Object Identification Tool. 2. Select "Web" from the "Environment" drop-down list. 3. You will most likely see "name" under the "Mandatory" or "Assistive" properties lists. Select "name" and remove it from the list. 4. You should not have any properties listed under "Mandatory" or "Assistive," but you should have "CreationTime" selected in the "Ordinal identifier" drop-down list. 5. Click <OK> and record a new test. In the new test, the Browser objects should no longer pick up the "name" property, but instead use "CreationTime". Option2: If it's necessary to use the "name" property, then use a regular expression. If you must use the "name" property to identify the browsers, use a regular expression to handle the dynamic portion of the name. For information on using regular expressions, please refer to Problem ID 6069 - How to use regular expressions (or wildcards). Option3: Use SetTOProperty to change the "name" value while running the test. The SetTOProperty method allows you to change the value of a property for an object in the Object Repository during a test run. Here is an example that will change the value of the "name" property of the Browser object "kirk : Delete", to "bob : Delete": Browser("kirk : Delete").SetTOProperty "name", "bob : Delete" You would need to run this line at the beginning of your test and pass in the new "name" property value.

Solution: Using regular expressions Regular expressions enable Astra QuickTest/QuickTest Professional (AQT/QTP) to identify objects and text strings with varying values. You can use regular expressions when defining the properties of an object, when parameterizing a step, and when creating checkpoints with varying values. A regular expression is a string that specifies a complex search phrase. By using special characters such as a period (.), asterisk (*), caret (^), and brackets ([ ]), you define the conditions of the search. When one of these special characters is preceded by a backslash (\), AQT/QTP searches for the literal character. Regular expression syntax: AQT/QTP searches for all characters in a regular expression literally, except for the regular expression characters, such as a period (.), brackets ([ ]), and a asterisk (*) as described below. When one of these special characters is preceded by a backslash (\), AQT/QTP searches for the literal character. The following options can be used to create regular expressions (this is not an allinclusive list): backslash (\) - Instructs AQT/QTP to treat the next character as either a special character if it is otherwise an ordinary character, or a literal character, if it is otherwise a special character. period (.) - Instructs AQT/QTP to search for any single character. brackets ([]) - Instructs AQT/QTP to search for any single character within a list of characters, not in a list (when used with the caret), or within a range (when used with a hyphen "-"). caret (^) - Instructs AQT/QTP to match the expression only at the start of a line, or after a newline character. When used with brackets, instructs QuickTest to search for a character not in the specified list. asterisk (*) - Instructs AQT/QTP to match zero or more occurrences of the preceding character. plus sign (+) - Instructs AQT/QTP to match one or more occurrences of the preceding character. question mark (?) - Instructs AQT/QTP to match zero or one occurrences of the preceding character. parentheses (()) - Instructs AQT/QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. dollar sign ($) - Instructs AQT/QTP to match the expression only at the end of a line, or before a newline character. vertical line (|) - Instructs AQT/QTP to match one of a choice of expressions. For additional regular expression options and a more detailed explanation of the above options, please refer to the User's Guide.

Example 1: [O|o]rder number [^0][0-9]+ The regular expression at the beginning of the line instructs AQT/QTP to match the word order if the "o" is either lowercase or uppercase. This can be useful if your application uses a font where multiple characters look the same, such as an upper case I, a lower case l, and the number 1. You could use the a regular expression to tell AQT/QTP to match the text if any of those characters are used in the specified location. The regular expression sequence at the end of the line instructs AQT/QTP to match an order number that starts with any character that is not a zero and is followed by one or more digits. Example 2: For another example demonstrating how to build more complex regular expressions, please refer to Problem ID 23770 - How to use a Regular Expression to match a range of numbers or Problem ID 37449 - How to verify a number in a field has the correct format (using regular expressions). Regular expressions can be used in the following cases:

• •

Within the object description of a window or object in the Object Repository. For more information, please refer to Problem ID 13698 - The dynamic text property of a link is causing replay problems Within a parameterized step in your test tree. Within an object checkpoint for a property or value that can vary. For more information, please refer to Problem ID 24315 - Checkpoints recorded in Internet Explorer do not replay on Netscape. Within a text checkpoint for a varying string. For more information, please refer to Problem ID 19294 - How to have a checkpoint ignore dynamic text.

For more information on how to use regular expressions in the above situations, please refer to the User's Guide. Note: When using regular expressions in object or step descriptions and in checkpoints, you must select the "Regular Expression" checkbox for AQT/QTP to check for the regular expression.
45. How to write data to an Excel file without importing the data to the data table

This function will allow you to set data in an external Excel file (specifying the sheet and the cell), without importing the file to the QuickTest data table. The function uses automation objects to create an Excel object.

Note: This function is not part of QuickTest Professional. It is not guaranteed to work and is not supported by Mercury Technical Support. You are responsible for any and all modifications that may be required. PutValueInFile (sfilePath, isheet, irow, icolumn, value) sfilePath isheet irow icolumn value The path and name of the Excel file. The sheet of the Excel file. This can be an index number or the sheet name. The row number in the table. The column number in the table. The value to put within the defined cell in the specified sheet.

Function PutValueInFile (sfilePath, isheet, irow, icolumn, value) Set ExcelObj = CreateObject("Excel.Application") ExcelObj.Workbooks.Open sfilePath Set NewSheet = ExcelObj.Sheets.Item(isheet) NewSheet.Cells(irow,icolumn) = value ExcelObj.ActiveWorkbook.Save ExcelObj.Application.Quit Set ExcelObj = Nothing End Function Example: filename = "D:\temp\Test.xls" PutValueInFile filename,1,2,2,"Hello From QTP!"
46 Retrieve data from excel sheet and write it to database: Dim oConn, rs  Set oConn = CreateObject("ADODB.Connection")  oConn.Open "Driver={Microsoft ODBC for Oracle};" & "Server=ENBPT2;" & "Uid=ptedb1;" &  "Pwd=ptedb1"  set rs=CreateObject("ADODB.recordset") sql = "SELECT ACCOUNT_ID FROM ( SELECT ACCOUNT_ID,ROWNUM RN FROM  AR1_ACCOUNT WHERE ROWNUM < 4 ) WHERE  RN = 3" rs.Open sql, oConn  a=rs.fields("ACCOUNT_ID") 'msgbox (a) 'msgbox(rs.GetString) 'For each x in rs.fields 'a=x.value 'msgbox(X) ' a=rs

'msgbox(a)  ' next  'msgbox("done")

'sfilePath 'The path and name of the Excel file.  'isheet 'The sheet of the Excel file. This can be an index number or the sheet name.  'irow The row number in the table.  'icolumn The column number in the table.  'value The value to put within the defined cell in the specified sheet.  Function PutValueInFile (sfilePath, isheet, irow, icolumn, value)    Set ExcelObj = CreateObject("Excel.Application")    ExcelObj.Workbooks.Open sfilePath    Set NewSheet = ExcelObj.Sheets.Item(isheet)    NewSheet.Cells(irow,icolumn) = value    ExcelObj.ActiveWorkbook.Save    ExcelObj.Application.Quit    Set ExcelObj = Nothing End Function  filename = "C:\Documents and Settings\x108536\Desktop\mm.xls" PutValueInFile filename,1,2,4,a

50.

Open IE

'Set the variable to "NS" for Netscape or "IE" for Internet Explorer. Browser1 = "IE"  StartURL = "www.yahoo.com"  IF Browser1 = "IE" THEN     set IE = CreateObject("InternetExplorer.Application")     IE.Visible = true     IE.Navigate StartURL  END IF  IF Browser1 = "NS" THEN     SystemUtil.Run "netscp6.exe", StartURL, "C:\Program Files\Netscape\Netscape 6\", "" END IF

51 Close all the browsers: Public Function GetTaskManagerSpecificProcessList(obj) cols = obj.ColumnCount rows = obj.GetROProperty("items count") sSpecReport = "" numberOfProcess = 0 cc = 0 For rr = 0 to rows -1

regexpwndclass

If obj.GetSubItem(cInt(rr), cInt(cc)) = "IEXPLORE.EXE" Then numberOfProcess = numberOfProcess + 1 End If Next GetTaskManagerSpecificProcessList = numberOfProcess End Function SystemUtil.CloseProcessByName("iexplore.exe") OPEN A NEW BROWSER and navigate to google : URL = "www.google.com" set IE = CreateObject("InternetExplorer.Application") IE.Visible = true IE.Navigate URL

Exercise 2 Answer: URL = "www.google.com" set IE = CreateObject("InternetExplorer.Application") IE.Visible = true ' IE.maximized=true IE.Navigate URL Browser("Title:=Google").Page("Title:=Google").Webedit("html tag:=Input").set "mahesh" Browser("Title:=Google").Page("Title:=Google").Webbutton("Name:=Google Search").click
53. Verify Checkpoints using If else

Problem Description: How to verify a status bar message that disappears quickly The user needs to verify that the correct error message appears in a status bar in his application. The error message will appear and disappear before he can create a checkpoint against it in the script. How can he verify the message?

Solution: Create a checkpoint against the status bar object then modify the expected value Work-around 1: 1. Create a checkpoint against the status bar in the location of the script where the error message should appear.

2. Right-click on the checkpoint and choose the "Checkpoint Properties" option. 3. Manually modify the "statusbartext" property to have the expected error message. Work-around 2: 1. Create a checkpoint against the status bar in the location of the script where the error message should appear. 2. Replace the checkpoint method with the GetROProperty("statusbartext") method. Example: ' Change Browser("Yahoo!").WinStatusBar("msctls_statusbar32").Check CheckPoint("msctls_statusbar32") ' to sbtxt = Browser("Yahoo!").WinStatusBar("msctls_statusbar32").GetROProperty("statusbartext") 3. Use If..Then logic to verify the text is what you expect. 4. Use Reporter.ReportEvent to write a pass/fail message to the test results. Create a checkpoint against the status bar object then modify the expected value
56. How to retrieve the return value from a checkpoint The "Check" method now returns a Boolean return value. True means that the checkpoint passed and False  means that it failed. You can use this value in the script, for example, in an If statement. However, you must  modify the checkpoint to wrap the parameter in parentheses. 

Example: The statement originally Browser("...").Page("...").Image("...").Check Checkpoint("...") becomes retval = Browser("...").Page("...").Image("...").Check(Checkpoint("...")) rel=Window("TPX (AB)").WinObject("REFLECTION_EIGHT_DISPLAY").Check (CheckPoint("SERVICE REQUEST HAS BEEN")) msgbox(rel) 57. How to click on a link, then the Back button, and repeat the process for all links in a webpage

This example was created against http://www.google.com. ' Get a collection of all the links for the page Set oDesc = Description.Create() oDesc("micclass").Value = "Link" Set links = Browser("Google").Page("Google").ChildObjects(oDesc) ' Go through each link and click on it. For i=0 to links.Count - 1 ' You need to get the collection each time you click on the link. The collection will ' be destroyed each time you navigate to a new page. Set links = Browser("Google").Page("Google").ChildObjects(oDesc) ' Next two linkes are just for debug so you can see which link it clicks on. links(i).Highlight wait 1 links(i).Click Browser("Google").Sync Browser("Google").Back Browser("Google").Page("Google").Sync Next

60 How to return the total number of links in a webpage and their names and URLs Use the ChildObjects method to retrieve all the links on the specified webpage. Once you have the collection, you can use the GetROProperty method to retrieve the innertext (name) and href (URL) values. object.ChildObjects (pDescription) object A Page or Frame object. pDescription The description of the object to retrieve. Use the Description object to store the description of the object type to retrieve. For more information, refer to Problem ID 30068 - How to have a variable hold the description of an object. For information on using GetROProperty, refer to Problem ID 6028 - How to retrieve the runtime property of an object.

Example: ' The sample was created against www.google.com Set oDesc = Description.Create() ' Retrieve HTML tag <A> oDesc("html tag").Value = "A" Set rc = Browser("Google").Page("Google").ChildObjects(oDesc) num = rc.Count() For i=0 to num-1 tag = rc(i).GetROProperty("innertext") href = rc(i).GetROProperty("href") Reporter.ReportEvent 0, "Links in Page", "name: " & tag & "; url: " & href Next

63
Get the links and number of links: Set oDesc = Description.Create() oDesc("micclass").Value = "Link" Set links = Browser("Google").Page("Googlem").ChildObjects(oDesc)  msgbox links.count ' The sample was created against www.google.com ' The sample was created against www.google.com Set oDesc = Description.Create() ' Retrieve HTML tag <A> oDesc("html tag").Value = "A"  Set rc = Browser("Google").Page("Googlem").ChildObjects(oDesc) num = rc.Count() For i=0 to num­1    tag = rc(i).GetROProperty("innertext")    href = rc(i).GetROProperty("href")    Reporter.ReportEvent 0, "Links in Page", "name: " & tag & ";    url: " & href Next

64 To pass parameter to database connection:

oConn.Open "Driver={Microsoft ODBC for Oracle};" & "Server=" & S & ";" & "Uid=" & Ui & ";" &  "Pwd=" & pw & " 65

Problem Description: How to lock the keyboard and mouse during replay In certain situations, the user may wish to lock the mouse and keyboard during replay. This way, the test run will not be disturbed by the user sitting next to the machine.

Solution: Use the BlockInput method to lock the mouse and keyboard during replay QuickTest Professional 9.0 and above QuickTest Professional 9.0 and above have a built in method called BlockInput, which is part of the SystemUtil object. BlockInput prevents keyboard and mouse input events from reaching applications. SystemUtil.BlockInput You can use this method to prevent a run session being accidentally interrupted by someone using the keyboard or mouse on a QuickTest Professional computer. After using this method, keyboard and mouse input is blocked until one of the following occurs:
• • • •

An UnblockInput statement is used A run session ends or is paused for any reason (end of test run, run error, breakpoint, and so forth) The Ctrl+Alt+Delete key combination is pressed on the keyboard A critical system error occurs

SystemUtil.UnblockInput The UnblockInput method can be used to unblock keyboard and mouse input that was earlier blocked using a BlockInput statement. Example: ' Launch the sample flight app 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" ' Block keyboard and mouse input during replay SystemUtil.BlockInput wait 10 ' While waiting, try to manually enter an agent name

' enter the username and password Dialog("Login").WinEdit("Agent Name:").Set "mercury" Dialog("Login").WinEdit("Password:").SetSecure "457dcee06850fd977afb7d635d57cd3157d935ea" ' Unblock keyboard and mouse input SystemUtil.UnblockInput

67.

Problem Description: How to capture text from a tooltip When the user moves the mouse over some objects in his application, a tooltip appears. Is there a way to capture the text displayed in the tooltip?

Solution: Capture the text property for the tooltips_class32 control 1. Move the mouse over the object. If you are testing Web objects, use the MouseOver method, otherwise use the MouseMove method. For more information on the MouseMove method, please refer to Problem ID 22528 - How to move the mouse cursor from within a script. 2. Wait a second or two for the tooltip to appear. 3. Use descriptive programming to refer to the tooltip object. Most window applications use the "tooltips_class32" class for tooltips. Use the descriptive programming to find the object of that class. 4. Use GetROProperty to capture the text of the tooltip. Example: ' Windows applications ' Move the mouse over the object. Window("TextPad").WinObject("Standard").MouseMove 22,15 ' Wait a second to allow the tooltip to be displayed. wait 1 ' Capture the text of the tooltip object txt= Window("nativeclass:=tooltips_class32").GetROProperty("text") msgbox txt ' Browser-based application ' Mouseover the object. Browser("Browser").Page("Page").Link("Link 1").MouseOver ' Wait a second to allow the tooltip to be displayed. wait 1 ' Capture the text of the tooltip object

txt= Window("nativeclass:=tooltips_class32").GetROProperty("text") msgbox txt Note: If your application uses a different class of object for the tooltip, you may need to use the "Object Spy" (Tools -> Object Spy) to spy on the tooltip to determine the class. After you click the hand button on the Object Spy window, the mouse cursor will turn to a hand icon. Press and hold the CTRL key to change the cursor to the normal state. Mouseover the control to bring up the tooltip. Once the tooltip is up, release the CTRL key and click on the tooltip immediately, before it disappears. If you cannot use the Object Spy to determine the class of the tooltip object, you may need to contact your developer for this information. Set the name of the file to be saved (should be different for each ReportEvent statement) filename = "DescImage" ' The object to capture the bitmap from set obj = Browser("The customer support site").Page("The customer support site").WebEdit("username") ' Capture the bitmap to the path of the results obj.capturebitmap reporter.ReportPath & "\\" & filename & ".bmp" ' Report the results and point to the captured bitmap file reporter.ReportEvent 0,"Desc","This step passed: <img src='" & reporter.ReportPath & "\\" & filename & ".bmp" & "'>" There are several ways this could be functionalized, depending on your needs. Here are a few examples: ' objSendBitmap - sends normal status to results with an image displayed Public Function objSendBitmap(obj, filename) obj.capturebitmap reporter.ReportPath & "\\" & filename & ".bmp" reporter.ReportEvent micDone,"objSendBitmap","Object Image: <img src='" & reporter.ReportPath & "\\" & filename & ".bmp" & "'>" End Function ' objReportBitmap - sends desired results status to results with an image displayed Public Function objReportBitmap(obj, filename, status) Dim message obj.capturebitmap reporter.ReportPath & "\\" & filename & ".bmp" Select Case status Case micPass message = "Step success image: "

Case micFail message = "Step failure image: " Case micWarning message = "Step warning image: " Case micDone message = "Step image: " Case Else message = "Warning - Invalid event status. Step image: " status = micDone End Select reporter.ReportEvent status,"objReportBitmap",message & "<img src='" & reporter.ReportPath & "\\" & filename & ".bmp" & "'>" End Function Note: When you view the results after replay, the HTML code (for example, "<img src='image.bmp'>") will be displayed in the results, not the image you are expecting. You can get around this one of two ways: 1. Add the HTML tag for a left angle bracket ("&lt;") to the line before the actual image tag. Example: Reporter.ReportEvent micDone, "Image", "&lt;<img src='image.bmp'>&gt;" When you view the test results with the above line, you will see the actual image as expected. Note that the angle bracket (<) will also be displayed next to the image. 2. If you are using QuickTest Professional 8.0 and above, you can modify the results.xml file to specify that HTML tags should be displayed as actual HTML objects, not text. The Details element will specify how the details of the report should be displayed. For more information on the schema used by the results, refer to the Results Schema Appendix in the QuickTest Professional User's Guide. By default, the Details element is set to False, which instructs the test results viewer to display the HTML code as plain text. Example: <!ELEMENT Details ( #PCDATA ) > <!ATTLIST Details plainTxt (False|True) "False"> Open the results.xml file for your test results (in the "<results location>\Report" directory) and find the Details element. Change the "False" to "True."

Example: <!ELEMENT Details ( #PCDATA ) > <!ATTLIST Details plainTxt (False|True) "True"> For information on how to change this setting at runtime, refer to Problem ID 40004 How to display HTML objects in the test results.

Problem Description: How to register a user-defined function for use with objects The user created some custom functions that he would like to use to replay against QuickTest Professional object classes. How can this be done?

Solution: Use the RegisterUserFunc statement The RegisterUserFunc statement instructs QuickTest Professional to use your userdefined function as a method of a specified test object class for the remainder of a test run, or until you unregister the method. If the specified method name does not already exist for the test object, it becomes a new method for the object. If the method name is a defined QuickTest Professional method for the object, your definition (temporarily) overrides the existing functionality of the specified method. Note: You cannot register a method for a QuickTest reserved object (such as DataTable, Environment, Reporter, etc.). RegisterUserFunc TOClass, MethodName, FunctionName TOClass - The test object class for which you want to register the method. MethodName - The method you want to register. FunctionName - The name of your user-defined function. The function can be located in your test, or in any library file associated with your test. To override an existing method, the MethodName parameter should be the name of the method to be overridden and the FunctionName parameter should be the name of your custom function. Then, you would call the standard method. During replay, QuickTest Professional will use your function. Note: If you are overriding an existing method, the custom function should use the same parameters. Example: ' Register the MySet function for use when the Set method is executed.

RegisterUserFunc "WebEdit", "Set", "MySet" ' Call the method. Browser("MercuryTours").Page("FindFlights").WebEdit("Country").Set "Canada" To use your function as an extension to the existing methods, both the MethodName and FunctionName parameters should be the name of your custom function. Then, to use the function, you would call it using your function's name. Example: ' Register the MySet function for use. RegisterUserFunc "WinEdit", "MySet", "MySet" ' Call the MySet function. Dialog("Open").WinEdit("File name:").MySet "document.txt" Notes:
• •

• •

When a function will be used as a registered function, the first parameter in the function will be the test object. If you are overriding an existing method, the new function should have the exact syntax of the method it is replacing. This means that its first argument is the test object and the rest of the arguments match all the original method arguments. A registered method applies only to the test in which you register it (or to any tests calling the action containing a RegisterUserFunc statement). If you register a function within a reusable action, it is recommended that you unregister the method at the end of the action (see the UnregisterUserFunc statement below) . QuickTest clears all function registrations at the beginning of each test run.

The UnregisterUserFunc statement instructs QuickTest Professional to stop using the current registration of the method. If the unregistered method is a defined QuickTest Professional method for the object, the functionality of the method returns to the standard QuickTest Professional functionality. UnRegisterUserFunc TOClass, MethodName TOClass - The test object class for which you want to unregister the method. MethodName - The method you want to unregister. Example: ' Register the MySet function for use when the Set method is executed. RegisterUserFunc "WebEdit", "Set", "MySet" ' Call the method. Browser("MercuryTours").Page("FindFlights").WebEdit("Country").Set "Canada" ' Return the Set functionality to the standard QuickTest Professional functionality. UnRegisterUserFunc "WebEdit", "Set"

Use the RegisterUserFunc statement

Problem Description: How to get a list of a Menu's subitems (WinMenu) The user would like to get a list of the submenu items for a specified menu option. Example: File New Open Save In the above example, the user wants to get the list "New;Open;Save" if he specifies "File." How can this be done?

Solution: Use the custom GetMenuItems function Use the WinMenu object's GetItemProperty method to retrieve the labels of the menu items. Note: This function is not part of QuickTest Professional. It is not guaranteed to work and is not supported by Mercury Customer Support. You are responsible for any and all modifications that may be required. Function GetMenuItems( oMenu, Itm ) MenuCnt = oMenu.GetItemProperty( Itm, "SubMenuCount") Menu_Items = "" For i=1 to MenuCnt ' Build a path to a submenu mPath = Window("Notepad").WinMenu("Menu").BuildMenuPath(Itm, i) ' Capture the label of the submenu Menu_Items = Menu_Items & oMenu.GetItemProperty(mPath, "Label") If i < MenuCnt Then Menu_Items = Menu_Items & ";" End If Next GetMenuItems = Menu_Items End Function RegisterUserFunc "WinMenu", "GetMenuItems", "GetMenuItems"

The RegisterUserFunc method registers the function for use with a QuickTest test object. For more information, please refer to Problem ID 25943 - How to register a user-defined function for use with objects. Example: Window("Notepad").Activate MenuItems = Window("Notepad").WinMenu("Menu").GetMenuItems ("Edit") MsgBox MenuItems The GetMenuItems function will return the list of submenu items as a string separated by a semicolon (;). You can split this string if you need the individual labels of the menu items. Example: MenuItems = Window("Notepad").WinMenu("Menu").GetMenuItems ("File") MsgBox MenuItems Arr = split (MenuItems,";") For i=0 to UBound(Arr) MsgBox Arr(i) Next

Problem Description: "File -> Close" is not recorded The user's business process includes the opening and closing of the browser. But the action "File -> Close" is not recorded.

Solution: Closing the browser Astra QuickTest doesn't record actions on the Menu. To record and replay closing the browser, close the browser by clicking on the "X" in upper right corner of the browser. Closing the browser

Problem Description: How to add objects to the Object Repository programmatically (QTP 6.5 - 8.2)

Solution: Use the ObjectRepositoryUtil API functions from QuickTest Plus The QuickTest Plus files contain documentation on how to access the Object Repository from within the script. For information on how to get the QuickTest Plus files, refer to Problem ID 18799 - How to get the QuickTest Plus file updates. Note: The information in QuickTest Plus is provided on an as-is basis. While efforts were made to ensure the accuracy of the information and utilities provided, Mercury cannot guarantee that all information is up-to-date and that all utilities and code samples work as expected. Additionally, compatibility of the included information and utilities with any future release of QuickTest cannot be guaranteed. Mercury Customer Support Organization may not be able to provide support for problems encountered while using QuickTest Plus. To access the Object Repository API functions: 1. Install the QuickTest Plus files. 2. Select the SDK link (or the SDK -> SDK branch in the tree). 3. Select the "External API to the Object Repository" link. The documentation will open in Word. The documentation includes information on the API functions and examples. All test objects in QuickTest Professional are COM objects, so you can basically just do a "create object" as long as you know the ProgID. The following example illustrates how to create a new Test Object, set its properties and add it to the shared Object Repository. The example works with the attached sample script but you need to modify the path unless you unzip the script to the path C:\temp\login. Example: ' Load the Object Repository in question Set oru = CreateObject ("Mercury.ObjectRepositoryUtil") oru.LoadActionRepository "C:\Temp\Login","Action1" ' Get Parent Object of which we want to add the new Test Object under Set ParentObj = oru.GetObjectByParent( NULL, "Dialog(""Login"")" ) ' Create a new Test Object ( A Stdbutton in this case ) and set the ' properties for this object set StdButton = CreateObject("Mercury.WinButton") StdButton.SetTOProperty "text","Cancel" StdButton.SetTOProperty "nativeclass","Button"

' Add the new Test Object (StdButton) to the parent object ' ( DialogBox). Set the logical name of the new Test Object to "Cancel" oru.AddObject StdButton, ParentObj, "Cancel" ' Save the changes and release the objects oru.Save Set ParentObj = nothing Set StdButton = nothing Set oru = nothing You can find a complete list of the different test objects in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest\Test Objects. Note: Remember to add "Mercury.XXXXX" when you create the Test Object. If you receive an "ActiveX component can't create object: 'Mercury.xxxx'" error message, the required ProgID value may not be correct. For example, to create a Dialog object, you would need to use "Mercury.WinDialog", not "Mercury.Dialog". To determine the correct ProgID values for these objects, do the following: 1. In the registry, navigate to the key mentioned above. 2. Locate the desired test object. Example: Dialog 3. Right-click on the CLSID value for that test object and select Modify. 4. Copy the value data. Important: Make sure you do not modify the value. 5. Click <Cancel> to close the dialog. 6. Select the HKEY_LOCAL_MACHINE\SOFTWARE\Classes branch. 7. Go to Edit -> Find. 8. Paste the copied value into the Find what field. 9. Click <Find> or <Find Next>. The search will locate the CLSID value under the appropriate ProgID. This is the value you should use in the CreateObject statement. Example: Mercury.WinDialog

The ProgID_List.htm file in the attached .ZIP file contains a list of Test Objects for the built-in environments (standard windows, Web, ActiveX, and Visual Basic). This list can be used as a reference for the ProgIDs for objects in these environments. In the file, locate your Test Object and use the associated ProgID. Some ProgID values do not match the Test Object names exactly (potentially resulting in the error above). In the file, these values are displayed in red to make them easier to see. Attachment : CPT29448.zip 1-21951801 Use the ObjectRepositoryUtil API

Problem Description: How to copy/cut and paste objects in the Object Repository (QTP 8.2 and below) While creating a script, QTP learns the same parent object, such as a window, into the Object Repository multiple times. Each instance of the parent object contains different child objects. Can these objects be merged under the same parent object?

Solution: Use the Object Repository API methods to copy/cut and paste objects This is a limitation of the Object Repository GUI. The QuickTest Plus files contain some API functions for working with the Object Repository. Using these API calls, you can write a script to move the objects from one parent object to another parent object. The example below does this. For more information on QuickTest Plus, refer to Problem ID 18799 - How to get the QuickTest Plus file updates. For information on the Object Repository API, refer to the QuickTest Plus files (QuickTest Plus -> SDK -> External API to the Object Repository) and to Problem ID 29449 - How to add objects to the Object Repository programmatically (QTP 6.5 - 8.2). Note: Mercury Customer Support may provide programming and software examples for illustration purposes only. Please note that these examples are not part of QuickTest Professional. They are not guaranteed to work and are not supported by Mercury Customer Support. You are responsible for any and all modifications that may be required. Important: Customer Support strongly recommends making a backup copy of your test scripts (or Shared Object Repository) before using this code.

1. Install QuickTest Plus if not already installed. The Object Repository API functions are located in the QuickTest Plus files. If QuickTest Plus is not installed, you will receive an "ActiveX component can't create object: 'Mercury.ObjectRepositoryUtil" error. Refer to Problem ID 18799 - How to get the QuickTest Plus file updates for information on how to get and install QuickTest Plus. 2. Copy the code to a .VBS file. 3. Modify the appropriate lines for your environment: The LoadActionRepository method will load the repository for the specified Action found in the given path. You can also use the Load method (refer to the QuickTest Plus documentation for more information) and specify the entire path to the repository file if preferred. For Shared Object Repositories, use the Load method. parent1 - This is the parent object you want to keep. The child objects will be moved under this object. parent2 - The parent object to move objects from. The child objects will be removed from this object. Note: If you use the wrong function (for example, LoadActionRepository to load a Shared Object Repository) for your environment, you will receive an error message. 4. Save the .VBS file. 5. Execute the .VBS file. Make sure the OR is not currently open in another application (such as QuickTest Professional). Note: You may receive a "Microsoft Visual C++" error (R6025 - pure virtual function call) error when running the code. Click <OK>, then verify the objects were correctly merged under the specified parent. The example was created and executed on a machine with QuickTest Professional 8.0. It should work with QuickTest Professional 6.5 also, but this was not tested. Example: '''' The child objects under parent2 are moved to parent1 and then deleted from the object repository. '''' Set Repository = CreateObject ("Mercury.ObjectRepositoryUtil") Repository.LoadActionRepository "C:\Program Files\Mercury Interactive\QuickTest Professional 80\Tests\OR_API_example", "Action1" Set parent1 = Repository.GetObject("Dialog(""Renameable Window"")") ' The first parent object. The one to keep Set parent2 = Repository.GetObject("Dialog(""Renameable Window_2"")") ' The second

parent object. The one to remove ' Get the objects in parent2 Set TOCollection = Repository.GetChildren(parent2) ' Copy the objects from the parent2 to parent1 For i = 0 To TOCollection.Count-1 Set newobj = Repository.CopyObject(TOCollection.Item(i)) ' Copy the object Msg = Repository.GetLogicalName(newobj) ' Get the logical name of the object Repository.AddObject newobj, parent1, Msg ' Add the object to parent1 next ' Remove the objects from parent2 For j = 0 to TOCollection.Count-1 set remobj = TOCollection.Item(j) Repository.RemoveObject parent2, remobj ' Remove the object from the parent2 object next Repository.RemoveObject NULL, parent2 ' Remove the parent2 object Repository.Save ' Save the changes to the repository. Note: The above code does not check for duplicates before copying the objects to the parent object. If this is a concern, you will need to make the necessary modifications to the code.

Problem Description: How to verify whether a menu item has a checkmark next to it (WinMenu) Some of the menu items in the application display a checkmark next to them when enabled. Is there a way to check for that checkmark?

Solution: Use the GetItemProperty method with the Checked property GetItemProperty(Item, Property) Item The full path of the menu item to select from the list. The path is composed of the menu item names or a numeric index separated by a semicolon. To specify the index of the item to select, use <Item #>. Index values begin with 1.

Note: You can use the BuildMenuPath method to build the item path string that can then be used as the Item argument for this method. Refer to the QuickTest Professional Object Model Reference for information on BuildMenuPath. Property Property to retrieve from the object. The following properties are available for use with the method: Returns a boolean value indicating whether the specified menu item has a check mark displayed next to it. Returns a boolean value indicating whether the specified menu item Exists exists. Returns a boolean value indicating whether the specified menu item is Enabled currently enabled. Returns a boolean value indicating whether the specified menu item has HasSubMenu a sub-menu. Returns the numeric index location of the specified menu item. Index Index values begin with 0. Label Returns the menu item label as a string. Returns the number of items contained in the specified menu item's subSubMenuCount menu (if any). Checked

Example: ' Check whether the View -> Toolbar menu item in the WordPad application is checked. msgbox Window("WordPad").WinMenu("Menu").GetItemProperty("View;Toolbar", "Checked") You can also use Win32 API to check the whether the menu item has a check mark next to it or not. If you have any questions about the API's listed below then please refer to the links below. Menu Functions http://msdn.microsoft.com/library/enus/winui/winui/windowsuserinterface/resources/menus.asp?frame=true About Windowing, has links to Windows functions, etc. http://msdn.microsoft.com/library/enus/winui/winui/windowsuserinterface/windowing.asp?frame=true Note: Mercury Customer Support may provide programming and software examples for illustration purposes only. Please note that these examples are not part of QuickTest

Professional. They are not guaranteed to work and are not supported by Mercury Customer Support. You are responsible for any and all modifications that may be required. Example: ' Constants taken from WinUser.h const MF_BYCOMMAND = 0 ' Indicates that the uId parameter gives the identifier of the menu item const MF_BYPOSITION = 1024 ' Indicates that the uId parameter gives the zero-based relative position of the menu item const MF_ENABLED = 0 ' The item is enabled const MF_GRAYED = 1 ' The item is disabled and grayed. const MF_DISABLED = 2 ' The item is disabled. const MF_CHECKED = 8 ' A check mark is placed next to the item (for drop-down menus, submenus, and shortcut menus only). const MF_POPUP = 16 ' Menu item is a submenu. const MF_MENUBARBREAK = 32 ' This is the same as the MF_MENUBREAK flag, except for drop-down menus, submenus, and shortcut menus, ' where the new column is separated from the old column by a vertical line. const MF_MENUBREAK = 64 ' The item is placed on a new line (for menu bars) or in a new column (for drop-down menus, submenus, and shortcut menus) without separating columns. const MF_HILITE = 128 ' The item is highlighted. const MF_OWNERDRAW = 1024 ' The item is owner-drawn. const MF_SEPARATOR = 2048 ' There is a horizontal dividing line (for drop-down menus, submenus, and shortcut menus only). ' You can find detailed information about each of the following function on MSDN ' MSDN Link: http://msdn.microsoft.com/library/default.asp?url=/library/enus/winui/winui/windowsuserinterface/resources/menus.asp Extern.Declare micLong,"GetMenu", "user32.dll", "GetMenu",micHwnd Extern.Declare micInteger, "GetMenuItemCount", "User32.dll", "GetMenuItemCount", micLong Extern.Declare micLong, "GetSubMenu", "user32.dll", "GetSubMenu", micLong, micInteger Extern.Declare micInteger, "GetMenuString", "user32.dll", "GetMenuString", micLong, micInteger, micString + micByRef , micInteger, micInteger Extern.Declare micInteger, "GetMenuState", "user32.dll", "GetMenuState", micLong, micLong, micLong Extern.Declare micLong , "IsMenu", "user32.dll", "IsMenu", micLong ' Get the Handle of the main window. Make sure you launch wordpad.exe before you run this example WinHandle = Window("title:=.* - WordPad", "index:=0").GetROProperty("hwnd")

' Get Handle Of Main Menu ( e.g File, Edit, View. etc ) MenuHandle = Extern.GetMenu ( WinHandle ) ' Get Handle Of "View" Menu ( 0= File, 1=Edit, 2=View etc ) FileMenuHandle = Extern.GetSubMenu ( MenuHandle, 2 ) ' Get Number if Items in the "FileMenu" FileItemsCount = Extern.GetMenuItemCount ( FileMenuHandle ) MsgBox "Number of menu items under the 'View' Menu bar: " & CInt(FileItemsCount) ' Get the label of the 1 item under 'View Menu' ( 0=ToolBar, 1=Format Bar etc) Extern.GetMenuString FileMenuHandle, 1, MenuText, 128, MF_BYPOSITION ' Get the check state of the 1 item under 'View Menu' ( 0=ToolBar, 1=Format Bar etc) If ( Cint ( Extern.GetMenuState ( FileMenuHandle, 1, MF_BYPOSITION ) ) And CInt( MF_CHECKED) ) = MF_CHECKED Then MsgBox MenuText + " is checked " else MsgBox MenuText + " is not checked " End if

Problem Description: The Tools -> Object Repository menu item is disabled The user has Astra QuickTest/QuickTest Professional set to use the Shared Object Repository mode. He has two Object Repository files he wants to use. When he switches between files, the Object Repository menu item (Tools -> Object Repository) becomes disabled. Example: 1. Open a new script in Astra QuickTest/QuickTest Professional. 2. Go to Test -> Settings. 3. Select the Resources tab. 4. Select the "Shared" radio button for the Object Repository type. 5. Set the name of the Shared Object repository file to Test1.tsr. 6. Click <Apply>. 7. Click <OK> on the QuickTest Professional information dialog if it appears. 8. Click <OK> to close the Test Settings dialog. A Test1.tsr file will be added to the <QuickTest>\Tests directory. 9. Start the sample Flight application. 10. Record entering the Agent Name. If you go to Tools -> Object Repository, the menu

option will be enabled. If you look in the file, there will be two objects (the Login window and the Agent Name edit field). 11. In Windows Explorer, copy the Test1.tsr file. Rename the copied file Test2.tsr. 12. Go to Test -> Settings. 13. Select the Resources tab. 14. Set the name of the Shared Object repository file to Test2.tsr. 15. Click <Apply>. 16. Click <OK>. 17. Go to Tools -> Object Repository. The option will be disabled. 18. Using steps 12 through 16, set the test to use Test1.tsr again. 19. Go to Tools -> Object Repository. The option is disabled again. 20. Record entering the password on the Login window. 21. Go to Tools -> Object Repository. The menu option is enabled, but when the Object Repository opens, only two objects are listed (the Login window and the password edit field) not the three that are expected (the Login window and the Agent Name and password edit fields). Diagnosis:The Object Repository files that are selected do not contain any objects. Since the files are empty, the menu option is disabled.

Solution: Save the Object Repository files The Object Repository menu option (Tools -> Object Repository) is only enabled when the Object Repository file contains objects. When you first open a new script, you will find the option disabled. After recording against an object, the option will be enabled because the file now contains information. A key thing to remember when working with Shared Object Repository files is that any changes or additions made to the Object Repository must be manually saved. To save the Object Repository, you must save the script. This is true when working with the PerAction mode also. Example: 1. Open a new script in Astra QuickTest/QuickTest Professional. 2. Go to Test -> Settings. 3. Select the Resources tab. 4. Select the "Shared" radio button for the Object Repository type. 5. Set the name of the Shared Object repository file to Test1.tsr. 6. Click <Apply>. 7. Click <OK> on the QuickTest Professional information dialog if it appears. 8. Click <OK> to close the Test Settings dialog. A Test1.tsr file will be added to the <QuickTest>\Tests directory. 9. Start the sample Flight application. 10. Record entering the Agent Name. If you go to Tools -> Object Repository, the menu option will be enabled. If you look in the file, there will be two objects (the Login

window and the Agent Name edit field). 11. Save the script. 11. In Windows Explorer, copy the Test1.tsr file. Rename the copied file Test2.tsr. 12. Go to Test -> Settings. 13. Select the Resources tab. 14. Set the name of the Shared Object repository file to Test2.tsr. 15. Click <Apply>. 16. Click <OK>. 17. Go to Tools -> Object Repository. The option will be enabled. When the Object Repository opens, you see the Login window and Agent Name edit field objects. 18. Record entering the password on the Login window. 19. Save the script. This saves the Test2.tsr file with the three objects. 20. Using steps 12 through 16, set the test to use Test1.tsr again. 21. Go to Tools -> Object Repository. The option is enabled and the Login window and Agent Name edit field objects are listed. 22. Using steps 12 through 16, set the test to use Test2.tsr again. 21. Go to Tools -> Object Repository. The option is enabled and the Login window, Agent Name edit field, and Password edit field objects are listed. Note: As of Astra QuickTest/QuickTest Professional 6.0, there is no way to save changes made in the Object Repository without saving the test script. As you make changes in the Object Repository, make sure you save the script.

Keyword driventesting is new concept in qtp. QTP has two views: 1.Keyword view 2. expert view in keyword view one can see the object ,the operation performed on it and it's value In keyword driven testing you use the recorded object to generate operations on it. i mean you select a object and press f7 or right click the mouse and select insert step menu.that way you can generate code without having to generate it manually. This is called keyword driven testing.Each object visible can be thaught of as keyword DataDriven testing: Datadrivent testing means testing the same functionality of application with different set of data to check whether it works on all kind of data.

For this case you parameterize a step in qtp,put alll the data values in datatable and run the script for number of iterations equal to number of rows in datatable.

Sign up to vote on this title
UsefulNot useful