Tuesday, July 28, 2009

QTP Tips

You can create multiple application areas to suit different components.
1. Business components associated with an application area use only the resources and settings that are defined in the application area. In previous versions of QuickTest Professional, business components could have custom settings.
The RegisterUserFunc statement now has an optional argument that you can use to set a function as the default operation for a test object.
You can use the new Function Definition Generator to easily generate user-defined functions (Insert > Function Definition Generator).
Iterations for a business component are defined in Quality Center.
The Operation item appears in the Keyword View only when functions are defined in function library files associated with the component’s application area.

2. You can manage the availability of keywords used to create keyword-driven components using the new Keywords pane in the application area of QuickTest Professional.
The Function Definition Generator enables you to add documentation that specifies exactly what a step using your function does. This description is shown in the Documentation column of the Keyword View for steps that use the function.

3. You can associate a function library with the open test by opening the function library and choosing File > Associate Library 'library_name' with 'test_name'.

4. You can check syntax errors by clicking CTRL + F7. If your script contains errors you can view them in the new Information pane.
When adding a new step using the Keyword View or Step Generator, you can select a new object from your application and it is automatically added to your object repository.
You can specify which columns you want to display in the Keyword View. Choose Tools > View Options or right-click any column header in the Keyword View.
You can specify the order in which columns are displayed in the Keyword View. Choose Tools > View Options or drag a column header to a new location in the Keyword View.
You can print the contents of the Keyword View to your Windows default printer, or preview it on screen before printing. Click the Print button or choose File > Print.
You can copy and paste or drag and drop steps in order to move them to a different location within the Keyword View.
You can enter a comment about a step in the Keyword View by clicking in the Comment cell. You can also enter a comment on a new line below the currently selected step by choosing Insert > Comment.
You can view the Documentation column in the Keyword View to read a summary of what the step does, in an easy-to-understand sentence.

5. You can copy the content of the Documentation column to the Clipboard by right-clicking any column header in the Keyword View and choosing Copy Documentation to Clipboard.
The Select Object for Step dialog box enables you to select a new object from your application. If you select an object in your application that is not in the object repository, the object is added to the object repository when you insert the new step.
If you are connected to Quality Center, you can view the current Quality Center connection by pointing to the Quality Center icon in the status bar. To open the Quality Center Connection dialog box, double-click the Quality Center icon.
If a Quality Center test or shared file (such as a shared object repository or Data Table file) is open when you disconnect from Quality Center, then QuickTest closes it.
To access QuickTest tests or components from Quality Center, select the 'Allow other Mercury products to run tests and components' check box (Tools > Options) and install the QuickTest Add-in for Quality Center (from the QuickTest Professional CD-ROM).

6. If a business component is currently open, clicking the New toolbar button creates a new business component document (and not a new test document). This also applies if an application area or function library is open.

7. You can open a recently used business component, application area, or function library by selecting it from the Recent Files list in the File menu.
You can specify test, action, or component parameters to pass values to and from your test or business component, and between actions in your test.
You can define test or action parameter variables using the Parameter object and its methods in the Expert View.
You can create test, action, or component parameter output values that retrieve values during the run session and store them for use at another point in the run session. You can then use these output values to parameterize a step in your test or business component.

8. You can create object repository parameters. When associating an object repository to a test asset, you map this parameter to a constant or a test asset parameter (test, action, or business component).
You can select an object in the object repository and locate it quickly in your application using the Highlight button in the ORM or ORE.

9. You can locate an object in the object repository by pointing to an object in your application. If the object exists in the object repository, it is highlighted.

10. You can now add new objects to the object repository using filtering capabilities. For example, you can choose to add only a selected type of object residing in a window or a web page/frame.

11. You can now associate multiple object repositories with an action or application area. In previous versions of QuickTest Professional, you could associate only a single object repository with a test asset.

12. You can export object repository content to an XML file and import a new object repository from an XML file.
The list of Utility objects available when you open the Step Generator from the Keyword View is a sub-group of the list available when you open the Step Generator from the Expert View.
Open XML format used for report information now enables you to easily customize run reports and integrate result information with other applications. Refer to the QuickTest online documentation for a detailed description of the report's XML elements.
You can export test results to an HTML file to easily view the test results when you are not working in a QuickTest environment.
You can write automation scripts to control virtually every QuickTest feature and capability using the objects, methods, and properties included in the QuickTest Professional automation object model.
Test object and method names are not case sensitive.
When you type VBScript keywords in the Expert View, the relevant VBScript syntax or blocks are added to the test script.
You can now locate specified text strings in the Expert View, and replace them with text strings that you specify. You can search for literal text or use advanced options to fine-tune your search.

13. You can select a block in the Expert View and press CTRL + M to comment this block. Press SHFT + CTRL + M to uncomment the block.

14. You can select a block in the Expert View and indent or outdent it by clicking the Indent or Outdent toolbar buttons.

15. You can control the layout of the QuickTest Professional Window by dragging and dropping panes to a dockable, floating, and tabbed mode.

16. To move a dockable pane without snapping it into place, press CTRL while dragging it to the required location.

17. To auto-hide all the tabbed panes, select the title bar of the active tabbed pane, right-click and choose Auto Hide.

18. When you rename a test object, you can choose whether to automatically update all occurrences of the test object, or manually change the names in steps that use the renamed test objects.

19. You can copy objects from a shared object repository to the local object repository in order to modify them.

20. You can use the Object Repository Merge Tool to merge objects from two shared object repositories into a single object repository.

21. You can associate shared object repositories with multiple actions simultaneously, using the Associate Repositories dialog box.

22. You can resolve missing resources (such as missing object repositories and actions), using the new Missing Resources pane.
You can print a single action or business component from the Keyword View (in table format) or the from the Expert View (in statement format).
In addition to Data Table output values, you can output values to environment variables or store a retrieved value in a test, action, or component parameter.
You can use the Advanced Windows Applications Options dialog box to modify how QuickTest records and runs tests on Windows applications. Choose Tools > Options > Windows Applications tab > Advanced.
You can save the resulting data from the run-time Data Table to a file by inserting a DataTable.Export statement to the end of your test.
To instruct QuickTest to wait for an object to open or appear during test run, use an Exist or Wait statement.
To stop an analog step in the middle of a test run, click Ctrl + Esc, then click the Stop toolbar button.
If you want to create a bitmap checkpoint of multiple objects, select the object in the Object Selection dialog box that includes all the objects you want your bitmap checkpoint to contain.
If you need to recover Active Screen files after you save a test without Active Screen files, re-record the necessary steps or use the Update Run option to recapture screens for all steps in your test.
You can use a PathFinder.Locate statement in your test to retrieve the complete path that QuickTest uses for a specified relative path based on the folders specified in the Folders tab.
To maximize performance, load only the add-ins you need.
You can define a recovery scenario to handle unexpected behavior during your run session.
You can add new objects to the Object Repository from the Active Screen or using the Add Objects option in the Object Repository dialog box and pointing to the object in your application.
To record keyboard input, mouse clicks, and the exact path the mouse travels, switch to Analog Recording mode or Low Level Recording mode.
If it takes time for an object you are checking to load all of its data, you can increase the checkpoint timeout.
You can insert XML output values to your script.
You can verify that your XML is structured according to a specific schema.
You can specify a relative path when calling actions, functions, and other external files associated with or referenced by a test or business component.

23. You can create library files (containing VBScript functions, subroutines, classes, modules, and so forth) in QuickTest Professional and associate them with your test or application area. You can then call these functions (or other elements) from within your test assets.

24. You can debug functions, subroutines and classes defined in a function library file in QuickTest Professional.
You can create a user-defined function and register it as a test object method in order to overwrite or add to existing test object functionality.
You can use the Data Driver Wizard to automatically parameterize constants in your action or business component.
You can use the Reporter object to disable or enable messages to the Test Results.
You can record a test on one version of Microsoft Internet Explorer and then run it on other browsers or versions.
To transfer control to the application while spying or inserting checkpoints on objects, press the CTRL key.
You can check the content of an image in a Web page when you create an image checkpoint using the Compare Image Content option.
You can use the Data Table to run the test several times, each time using different data.
By default, in order to conserve disk space, QuickTest does not save screen captures with your test results for steps that pass. You can change the default setting in the Tools > Options > Run tab.
The Active Screen loads faster if you clear the Load Images check box in the Web Page Appearance dialog box (Tools > Options > Active Screen tab > Advanced button).
You can create a custom report message from the Keyword View by choosing Insert > Report.
You can teach QuickTest to recognize any area of your application as an object by defining it as a virtual object.
From QuickTest, you can run WinRunner tests and call TSL functions in compiled modules. The results of the WinRunner test or function are integrated into the QuickTest test results.
To modify the text used for a text checkpoint, click the Configure button in the Text Checkpoint Properties dialog box.
You can configure an action for repeated use in your test and in other tests. Select the Reusable Action check box in the Action Properties dialog box (Edit > Action > Action Properties).
You can use the ExitAction statement to terminate an action before it finishes running, based on conditions you specify in your test.
You can run QuickTest tests from a Quality Center project and pass parameter values to the test.
You can set breakpoints in your test, and then use the Debug Viewer pane to view, set, or modify the current value of objects or variables.
You can call methods and retrieve and set COM object properties from the Expert View using the .Object property.
You can configure how QuickTest records events in Web applications. Choose Tools > Web Event Recording Configuration.
You can define custom environment variables for use in your test.
You can add logic to a checkpoint by using a Data Table formula.
You can set a parameter to use a random numeric value.
You can use the Window Script Host and the VBScript Runtime Library to further extend your test. For more information choose Help > QuickTest Professional Help > VBScript Reference.
You can use the Object Identification dialog box to configure the way QuickTest learns and recognizes objects.
You can run your test in Update mode to update values in your test or business component. You can choose to update checkpoint data, Active Screen images, and/or the descriptions of the objects in the object repository. Choose Automation > Update Run Mode.
You can choose a Web server accessible via a Local Area Network (LAN) or a Wide Area Network (WAN) when connecting to Quality Center. Click the Quality Center Connection button or choose File > Quality Center Connection.
The Open Test from Quality Center Project dialog box displays icons that indicate the version control status of each test in your project.
If you want to add the same comment to every action that you create, you can add the comment to an action template.

Saturday, July 4, 2009

Automation Fundamental Concepts

What is Test Automation ?

Software Test Automation is the process of automating the steps of manual test cases using an automation tool Or utility to shorten the testing life cycle with respect to time…

When application undergoes regression, some of the steps might be missed out or skipped which can be avoided in Automation…

Automation helps to avoid human errors and also expedite the testing process…

To implement the Test Automation detailed planning and effort is required


Automation saves time and effort which results in reduction of the Test life cycle…

Benefits of Automation
- Consistency of Test Execution
- Reducing cycle time of regression test cycles
- Data driven testing
- Repeatability
- Coverage
- Reliability
- Reusability of test wares

Automation life cycle is a subset of the entire test life cycle…
Automation planning can be initiated in parallel to the test planning phase…
Factors to be considered in automation planning,
Stability of AUT (Application under test)
No of regression cycles to be performed
Compatibility of App platform with testing tools
Cost benefit analysis (ROI)
Availability of skilled resources

Regression Testing & Automation
When Automation is applicable?

Regression Testing Cycles are long and iterative.

If the application is planned to have multiple releases / builds

If it’s a long running application where in small enhancements / Bug Fixes keeps happening

Test Repeatability is required

QTP At a Glance …..

Introduction to QTP
(QuickTest Professional)
“The Mercury advanced keyword-driven testing solution”
Technologies Supported
Default Support
1. Standard Windows applications
2. Web objects / Applications
3. ActiveX controls
4. Visual Basic applications

Additional QuickTest add-ins Support,
1. Java
2. Oracle
3. SAP Solutions,
4. .NET Windows
5. Web Forms,
6. Siebel,
7. PeopleSoft,
8. Web services,
and terminal emulator applications.

Testing Process with QTP

Quick Test Pro involves 3 main stages:
Creating Test scripts

Running Tests

Analyzing Test Results


Creating Tests
Create a test script by recording a manual test scenario on the AUT (Application Under Test) using QTP.

Quick Test Pro graphically displays each step users perform in the form of a collapsible, icon based tree view in QTP’s Keyword View.

Running Tests & Analyzing Test Results
Running Tests:
Once the test scripts are recorded / created, next step is to execute them…While running (executing) the tests Quick Test Pro connects to the web site or AUT and performs each operation in the test as performed manually while recording / creating tests (test scripts)…
Debugging Test : To identify and eliminate the defects in the test scripts.
Analyzing Test Results:
Once the test scripts are executed, test results and the summary can be viewed for result analysis.


Add-in Manager

Default Add-ins
ActiveX
Visual basic
Web

Other Add-Ins
Siebel
Java
SAP
Oracle
.Net and many more


QTP’s Add-in Manager facilitates the users to select the technology / environment from variety of environments suitable for the AUT (Application Under Test)

Once an add-in is loaded, users can record that application in its supported environment and thus QTP recognizes the objects specific to the application under test (AUT) as loaded through Add-in Manager.

It is critical for the users to know the development technologies / environment of AUT, and load right Add-Ins while invoking Quick Test Pro.




Record & Run Modes

Recording Modes
Normal
Analog
Low level

Run Modes
Normal
Fast
Update
Options -> General
Best Practices for General Options:
Deselect all check boxes except “Save data for integrating with performance testing …” and “Display Add-in Manager on startup” which is default setting.

Click on “Restore Layout” button to reset screens to the initial setting when QuickTest was first installed.

Options --> Run


Best Practices for Options for Run Mode:
Run Mode as Normal:
This ensures that the execution arrow appears to help with trouble shooting the tests.
Synchronization becomes better for the AUT (Application Under Test)

Test Results:
Deselect the option “View Results when run session ends”

Mercury Tool Integration:
Select "Allow other Mercury products to run tests and components“

Screen Capture:
Save step screen capture to results "On error and warnings"

Record and Run Settings




Best Practices for Record & Run Settings,
Set the options to configure QTP to "Record and run test on any open Windows- based application“

Set the option - This window will appear the first time you click on the Record button in the new test.

Manually recall this window by selecting Test Record and Run settings

QTP - Main Window





QTP - Main Window
Test Pane:
Test Pane contains two labs to view the tests,
- Keyword View
- Expert View

Keyword View:
Quick Test Pro displays your test in the form of a collapsible, icon based tree…

Expert View:
Quick Test Pro displays the source code (VB Script) of the tests in this view.





Data Table :
Data table assists in Parameterizing the tests…

Debug Viewer Pane :
It assists in debugging tests with the help of
Watch Expressions, Variables, and Command.

Quick Test Pro Commands :
The Quick Test Pro commands can be chosen from the menu bar or from a Tool bar.

File Tool bar :
File tool bar contains buttons for managing the test.


Test Tool bar :
Test tool bar contains buttons for the commands used when creating or maintaining the tests…







Debug Tool Bar :
It contains buttons for commands used when debugging the steps in the tests…




Action Tool Bar :
To view all actions in the test flow or to view the details of a selected action…

Working with Test Objects in QTP

Test Object Model Conceptualization

Applying the Test Object Model Concept

Viewing Object properties Using Object Spy

Demo on Test Object Model features of QTP



Mandatory properties:
For each Test Object class, Quick Test has list of mandatory properties…

Assistive properties:
Quick Test adds assistive properties one by one to the description until it has compiled a unique description…

Ordinal identifier:
If the combination of all defined mandatory and assistive properties is not sufficient to create a unique test object description, Quickest also records the value for the selected ordinal identifier.

Smart Identification:
A Smart Identification definition can help QuickTest identify an object, if it is present, even when the recorded description fails due to changes in one or more property values.

Test Object Model
How Quick Test Identifies objects during the test run?
Quick test searches for a run time object that exactly matches the description of the test object from the object repository it learned while recording…

Test Object :
Test Object is an object that Quick Test creates in the test to represent the actual object in the application…

Run Time Object :

It is the actual object in the web site or application on which methods are performed during the test run..

Test Object Model

Viewing object properties by Object Spy :
Using the object spy, users can view the properties of any object in an open application…


Viewing object methods and methods syntax using object spy…

Object Spy enables users to view both the run time object methods, the test object methods associated with an object and to view the syntax for a selected method…


Managing Test objects

Object Repository Dialog box :
- Per Action Mode
- Shared Action Mode


Managing Test objects
Identifying the Object :
- Logical Name
- Class

Viewing the Objects Property :

Type - Constant, Data table property ,variable parameter.
Property - Name of the Property
Value - The value of the property
- Smart Identifier
- Add/ Remove


Adding or Viewing New objects :
- Add New Objects
- Object spy
- Saves all the object properties and values from a per action object repository to a separate file for use as a shared object repository in another test…
- Modify the Test object properties
- Finding the Test object properties
- Modifying the Logical Names
Object Properties Modification
Users can modify the properties of the temporary version of the object during the test run with out affecting the permanent values in the object repository
- SetTOProperty
- GetTOProperty

Main phases of QTP testing Process
Preparing to record
Recording a session on the application
Executing the test
Enhancing your test
Debugging your test
Re-executing the tests on a new version of the application
Analyzing the test results
Reporting defects
Types of Checkpoints (Verification Process)





Parameterising Tests

Different Types of Parameters
Test & Action Parameters
Data Table
Environment Variable
Defining a Data Table Parameter
Adding Parameter Values to a Data Table
Modifying Steps Affected by Parameterization
Running and Analyzing a Parameterized Test

Creating Output Values

Creating an Output Value
Running and Analyzing a Test with Output Values

Using Regular Expressions

Regular Expression Syntax
Working with Regular Expressions
Running and Analyzing a Test with Regular Expressions

Dividing Tests into Multiple Actions

Working with Multiple Actions
Creating New Actions
Inserting Existing Actions
Parameterizing an Action
Running and Analyzing a Multi-action Test
Different Types of Actions

Recovery Scenarios

Defining Recovery Scenarios
Creating a Recovery File
Understanding the Recovery Scenario Manager Dialog Box
Understanding the Recovery Scenario Wizard
Welcome to the Recovery Scenario Wizard Screen
Select Trigger Event Screen
Specify Pop-up Window Conditions Screen
Select Object Screen
Set Object Properties and Values Screen
Select Test Run Error Screen
Select Processes Screen
Recovery Operations Screen
Recovery Operation Screen
Recovery Operation – Click Button or Press Key Screen
Recovery Operation – Close Processes Screen
Recovery Operation – Function Call Screen
Post-Recovery Test Run Options Screen
Name and Description Screen
Completing the Recovery Scenario Wizard Screen
Saving the Recovery Scenario in a Recovery File
Managing Recovery Scenarios

VB Script basics

Data Types



Variables & Constants
Declaring Variables
Naming Restrictions
Scope and Lifetime of Variables
Assigning Values to Variables
Scalar Variables and Array Variables
Creating Constants

Operators


Conditions & Looping

Conditional Statements
If...Then...Else statement
Select Case statement
Looping
Do...Loop: Loops while or until a condition is true.

While...Wend: Loops while a condition is true.

For...Next: Uses a counter to run statements a specified number of times.

For each...Next: Repeats a group of statements for each item in a collection or each element of an array.

Functions



Key areas in QTP
About the script structure
Object Identification Mechanism
Active screen customization
Actions (Simple, Nested, External, Re-usable)
Parameterization (Different Types)
Checkpoints (Programmatic Methodology)
Descriptive programming
Adv. Synchronization points
Exception Handling
Microsoft Automation Object Model


About the script structure




QTP Functions
sample 1 - Capturing the snapshot of the combo box control
Window("Flight Reservation").WinComboBox("Fly From:").CaptureBitmap "C:\mybmp.bmp",true

'sample 2 - Capturing the snapshot of the entire window
Window("Flight Reservation").CaptureBitmap "C:\mybmp.bmp"

'sample 3 - Getting all the items from the combo box
My_Cnt = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount
msgbox My_Cnt

For i = 1 to My_Cnt
' the combo box item index will start from zero.
My_item = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i-1)
Msgbox My_item
Next

'sample 4 - Getting the entire content of the combo box
Var_Content = Window("Flight Reservation").WinComboBox("Fly From:").GetContent
Msgbox Var_Content

'sample 5 - Selecting an item from the combo - Using Index
Window("Flight Reservation").WinComboBox("Fly From:").Select(5)

'sample 6 - Selecting an item from the combo - Using Value
Window("Flight Reservation").WinComboBox("Fly From:").Select("London")

'sample 7 - Selecting an item from the combo - Using Variable
Var_Item = "Zurich"
Window("Flight Reservation").WinComboBox("Fly From:").Select(Var_Item)

'sample 8 - Getting the value of selected item
Var_Sel = Window("Flight Reservation").WinComboBox("Fly From:").GetSelection
Msgbox Var_Sel

'sample 9 - Edit box functions
Window("Flight Reservation").Activate
Call wait(8)
Window("Flight Reservation").WinEdit("Name:").Set "DasDas“
Call wait(8)
Window("Flight Reservation").WinEdit("Name:").Type "tryhard“
Call wait(8)
Window("Flight Reservation").WinEdit("Name:").Set "DasDas“
Call wait(8)
Window("Flight Reservation").Activate
Call wait(8)
Window("Flight Reservation").ActiveX("MaskEdBox").Set "111111“




QTP Functions
' Some FUM's (Frequently Used Methods)

'GetROProperty
Var_Text = Window("Flight Reservation").WinEdit("Name:").GetROProperty("AttachedText")
Msgbox Var_Text
Var_Enab = Window("Flight Reservation").WinEdit("Name:").GetROProperty("Enabled")
Msgbox Var_Enab

'Exist
If Window("Flight Reservation").WinEdit("Name:").Exist(5) Then
Msgbox "The Editbox exists"
Else
Msgbox "The Editbox does not exist"
End if

'Wait
Wait(10) ' The QTP will sleep for 10 seconds

'Msgbox
Msgbox "Hello QTP"

Object Identification Mechanism

Object Identification
Simple script for object identification
Renaming the logical name (‘ok’ to ‘cancel’)
Change the text property of the control (“OK” to “Cancel”)
Properties to be avoided in Mandatory Prop List (“Hwnd”,“OK_2“)
Class Identification Mechanism (e.g. Winbutton up to the first level hierarchy QTP can classify)

User Defined & Virtual Objects
Demo on User Defined objects and mapping them with the standard class
Demo on virtual objects…

Active screen customization
Setting up the active screen with different options




Actions (Simple, Nested, External, Re-usable)

Standalone Actions
Nested Actions
Integration of Actions (Call from One Action to other)
Driver Action (Main Action)
Re-usable Actions
External Call for Actions
Action Parameter

Parameterization
Classifications of Parameterization
Test and Action Parameters
Data Table (Global & Action Specific)
Environment variables
Random Number

Demo on data table parameter using two parameters

Checkpoints (Programmatic Methodology)
Standard checkpoint

Update run

Descriptive Programming
Entering Programmatic Descriptions Directly into Statements
Browser("Mercury Tours").Page("Title:=Mercury Tours").WebEdit("Name:=Author", "Index:=3").Set "Mark Twain"

Using Description Objects for Programmatic Descriptions
Set MyDescription = Description.Create() MyDescription("text").Value = "OK" MyDescription("width").Value = 50 Window("Error").WinButton(MyDescription).Click

Adv. Synchronization Points
Demo: using tool menu options
Demo: wait property
Demo: programmatically
Demo: wait & exist

Exception Handling

Recovery Scenario Concepts
Recovery Process
Trigger Events
Recovery Operation
Post-recovery Operation

Automation Object Model

AOM Usage:

Users can use these objects, and their associated methods and properties, to write the programs that automatically configure Quick Test options and run tests

Explanation and demo on Object model






QTP Utility Functions - Database

msgbox My_dbquery(10)
Dim My_Query, MyDesc

Public Function My_dbquery(ord_no)

DataConn = "C:\Das\tozip\lib\flight32.mdb"
Set Conn = CreateObject("ADODB.Connection")
ConStr = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & DataConn & ";"
Conn.open(ConStr)

SQL = "SELECT Orders.Customer_Name FROM Orders Orders WHERE (Orders.Order_Number=" &ord_no &")"
Set recordset = Conn.execute(SQL)
while not recordset.EOF
My_Query = recordset("Customer_Name")
recordset.movenext
wend

recordset.close
Conn.Close

set recordset = Nothing
Set Conn = Nothing

My_dbquery = My_Query
End Function

QTP Utility Functions – File Operations

File Creation

CreateFile "C:","mytextfile.txt","hi how are you?"
Public Function CreateFile(filpath,filname,filcontent)
xml_file = filpath & "\" & filname
Dim fileobject, tf
Set fileobject = CreateObject("Scripting.FileSystemObject")
Set tf = fileobject.CreateTextFile(xml_file, True)
tf.Write (filcontent)
tf.Close
End Function

File Operations

Function CheckFileExists (FilePath)
' check if file exist
CheckFileExists = oFSO.FileExists(FilePath)
End Function

' *************************************************************************************
' Write data to file

' Parameters:
' FileRef - reference to the file
' str - data to be written to the file
' *************************************************************************************
Function WriteToFile (byref FileRef,str)
' write str to the text file
FileRef.WriteLine(str)
End Function

' *************************************************************************************
' Read line from file

' Parameters:
' FileRef - reference to the file
' *************************************************************************************

Function ReadLineFromFile (byref FileRef)
' read line from text file
ReadLineFromFile = FileRef.ReadLine
End Function

' *********************************************************************************************
' Closes an open file.
' Parameters:
' FileRef - reference to the file
' *********************************************************************************************
Function CloseFile (byref FileRef)
FileRef.close
End Function

'*********************************************************************************************
' Opens a specified file and returns an object that can be used to
' read from, write to, or append to the file.

' Parameters:
' FilePath - location of the file and its name
' mode options are:
' ForReading - 1
' ForWriting - 2
' ForAppending - 8
' *************************************************************************************

Function OpenFile (FilePath,mode)
' open the txt file and retunr the File object
set OpenFile = oFSO.OpenTextFile(FilePath, mode, True)
End Function

' *********************************************************************************************
' Closes an open file.

' Parameters:
' FilePathSource - location of the source file and its name
' FilePathDest - location of the destination file and its name
' *********************************************************************************************
Sub FileCopy ( FilePathSource,FilePathDest)
' copy source file to destination file
oFSO.CopyFile FilePathSource, FilePathDest
End Sub

' *************************************************************************************
' Delete a file.

' Parameters:
' FilePath - location of the file to be deleted
' *************************************************************************************
Sub FileDelete ( FilePath)
' copy source file to destination file
oFSO.DeleteFile ( FilePath)
End Sub

' ************** Example of calling the file functions **********************
FilePath1 = "D:\temp\FSO\txt1.txt"
FilePath2 = "D:\temp\FSO\txt2.txt"
FilePathDiff = "D:\temp\FSO\txt_diff.txt"

FilePath = "D:\temp\FSO\txt.txt"

set fold = FolderCreate ( "D:\temp\FSO\new")
set f = OpenFile(FilePath,8)
' = WriteToFile(f,"test line")
d = CloseFile(f)

set f = CreateFile(FilePath)

Fexist= CheckFileExists(FilePath)
d = WriteToFile(f,"first line")
d = WriteToFile(f,"second line")
d = CloseFile(f)
FileCopy "D:\temp\FSO\txt.txt","D:\temp\FSO\txt1.txt"
FileDelete "D:\temp\FSO\txt1.txt"

Excel Sheet Operations


Set objExcel = CreateObject("Excel.Application")
strPathExcel = "C:\Documents and Settings\Anandana\Desktop\QTPSamples\Reading From Excel Sheets\test.xls"
objExcel.Workbooks.open strPathExcel
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

For i=1 to 3
'For j=1 to 2
'msgbox Trim(objSheet.Cells(i, j).Value)
' Next
DataTable.SetCurrentRow i
DataTable("SL_No", dtGlobalSheet)=Trim(objSheet.Cells(i, 1).Value)
DataTable("Name", dtGlobalSheet)=Trim(objSheet.Cells(i, 2).Value)

Next

objExcel.Application.Quit
Set objExcel=Nothing

Email Operations

SendMail "cssdas@hp.com","hi","how r u",""

Function SendMail(SendTo, Subject, Body, Attachment)

Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then

Mail.Attachments.Add(Attachment)

End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing

End Function

XML

Option Explicit

Dim xmlFilePath
Dim xmlDoc
Dim nodeBook, nodeId, sIdXml, currNode

msgbox GetXMLAttribute("C:\QTP 8.2\Day 4\database.xml", "database/contact", "company")

msgbox GetXMLElement("C:\QTP 8.2\Day 4\database.xml", "database/contact[4]", "phone")

'********************************************************************************
' Function UpdateXMLAttribute
'********************************************************************************
Public Function UpdateXMLAttribute(xmlFilePath, xmlElement, xmlAttribute, NewXMLValue)

LoadXMLFile(xmlFilePath)
ReplaceAttributeValue xmlElement, xmlAttribute, NewXMLValue
SaveXMLFile (xmlFilePath)
Set xmlDoc = Nothing
End Function
'********************************************************************************
' End of Function UpdateXMLAttribute
'********************************************************************************
'********************************************************************************
' Function UpdateXMLElementData
'********************************************************************************
Public Function UpdateXMLElementData(xmlFilePath, ElementPath,ElementName, ElementIndex, NewElementData)

Dim CurrentNode, CurrentValue

LoadXMLFile(xmlFilePath)
Set CurrentNode = xmlDoc.selectSingleNode(ElementPath)
Set CurrentValue = CurrentNode.getElementsByTagName(ElementName)
CurrentValue.item(ElementIndex).text = NewElementData
SaveXMLFile (xmlFilePath)
Set xmlDoc = Nothing

End Function
'********************************************************************************
' End of Function UpdateXMLElementData
'********************************************************************************
' Function GetXMLAttribute
Public Function GetXMLAttribute(xmlFilePath, xmlElement, xmlAttribute)

Dim AttributeValue
LoadXMLFile(xmlFilePath)
AttributeValue = GetAttributeValue(xmlElement, xmlAttribute)
Set xmlDoc = Nothing
GetXMLAttribute = AttributeValue

End Function
'********************************************************************************
' End of Function GetXMLAttribute
'********************************************************************************
' Function LoadXMLFile
'********************************************************************************
Public Function LoadXMLFile(Path)

Set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0")
xmlDoc.validateOnParse = False
xmlDoc.async = False
xmlDoc.load(Path)

End Function
'********************************************************************************
' End of Function LoadXMLFile
'********************************************************************************
'********************************************************************************
' Function GetXMLElement
'********************************************************************************
Public Function GetXMLElement(xmlFilePath, xmlNode, xmlElement)
Dim CurrentNode, CurrentValue
LoadXMLFile(xmlFilePath)
Set CurrentNode = xmldoc.selectSingleNode(xmlNode)
Set CurrentValue = CurrentNode.getElementsByTagName(xmlElement)
GetXMLElement = CurrentValue.item(0).Text
End Function

'********************************************************************************
' End of Function GetXMLElement
'********************************************************************************

MSDN Integration

extern.Declare micLong,"GetForegroundWindow","user32.dll","GetForegroundWindow"

hwnd = extern.GetForegroundWindow()

If hwnd = 0 Then
Msgbox "Window Not Found"
ExitRun
Else
Msgbox "Window Found with Handle ”&hwnd

End if
Timed Msg-Box

MsgBoxTimeout (“Sample Text”,”Timed MsgBox”, 10)

Public Sub MsgBoxTimeout (Text, Title, TimeOut)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Popup Text, TimeOut, Title
End Sub


Text Location

l = -1 ‘Left
t = -1 ‘Top
r = -1 ‘Right
b = -1 ‘Bottom

Succeeded = TextUtil.GetTextLocation("16",0,l,t,r,b)
If Not Succeeded Then
MsgBox "Text not found"
else
x = (l+r) / 2
y = (t+b) / 2
Set dr = CreateObject("Mercury.DeviceReplay")
dr.MouseClick x, y, 0
End If

Keystroke Functions

'An example that presses a key using DeviceReplay.
Set obj = CreateObject("Mercury.DeviceReplay")

Window("Notepad").Activate

obj.PressKey 63

keyboard Values




Mouse Click Events


Solution: Use the custom user-defined sub RightMenuSelect
NOTE:
This function/sub is not part of Astra QuickTest/QuickTest Professional. It is not guaranteed to work and is not supported by Mercury Interactive Technical Support. You are responsible for any and all modifications that may be required.

The RightMenuSelect function selects the menu item at index "idx" from the pop-up menu that appears when right-clicking on an object.

Sub RightMenuSelect (menu, idx)
Set obj = CreateObject("Mercury.DeviceReplay")
Set WshShell = CreateObject("WScript.Shell")
menu.MakeObjVisible
x = menu.QueryValue("abs_x")
y = menu.QueryValue("abs_y")
obj.MouseClick x+5, y+5, 2
For i = 1 To idx
WshShell.sendKeys "{DOWN}"
Next
WshShell.sendKeys "{ENTER}"
set WshShell = nothing
Set obj = nothing
End Sub

Device Replay object to perform a right click operation on any object by retrieving the coordinates of the object.
 
Sub RightClickObj(Obj, Offset_x, Offset_y)

 x_coord = Obj.GetROProperty("abs_x")
 y_coord = Obj.GetROProperty("abs_y")
 Set dr = CreateObject("Mercury.DeviceReplay")
 dr.MouseClick x_coord + Offset_x, y_coord + Offset_y, 2

End Sub

HTML Functions

Syntax:
Browser(“Browser”).Page(“Page").Object.documentElement.innerHTML

Example:
htmlSrc = Browser("Welcome to HP-GDIC").Page("Welcome: Mercury Tours").Object.documentElement.innerHTML

Msgbox htmlSrc

System Operations

Running and Closing Applications Programmatically
Syntax:
SystemUtil.Run “file, [params], [dir] “

Example:
SystemUtil.Run “notepad.exe myfile.txt “

Clipboard Objects
The object has the same methods as the Clipboard object available in Visual Basic:
Clear
GetData
GetFormat
GetText
SetData
SetText
Set cb = CreateObject("Mercury.Clipboard")
cb.Clear cb.SetText "TEST"
MsgBox cb.GetText

Regression Testing & Automation

When Automation is applicable?

Regression Testing Cycles are long and iterative.

If the application is planned to have multiple releases / builds

If it’s a long running application where in small enhancements / Bug Fixes keeps happening

Test Repeatability is required

Automation Fundamental Concepts

What is Test Automation ?


Software Test Automation is the process of automating the steps of manual test cases using an automation tool Or utility to shorten the testing life cycle with respect to time…

When application undergoes regression, some of the steps might be missed out or skipped which can be avoided in Automation…

Automation helps to avoid human errors and also expedite the testing process…

To implement the Test Automation detailed planning and effort is required


Automation saves time and effort which results in reduction of the Test life cycle…

Benefits of Automation
- Consistency of Test Execution
- Reducing cycle time of regression test cycles
- Data driven testing
- Repeatability
- Coverage
- Reliability
- Reusability of test wares


Automation life cycle is a subset of the entire test life cycle…

Automation planning can be initiated in parallel to the test planning phase…

Factors to be considered in automation planning,
Stability of AUT (Application under test)
No of regression cycles to be performed
Compatibility of App platform with testing tools
Cost benefit analysis (ROI)
Availability of skilled resources