45 Test Automation

Basically Software Testing is 2 types 1) Manual Testing 2) Test Automation Manual Testing: Testing software manually is called Manual Testing. we can test all accepts of software manually. Below Testing Types can be tested manually Test Types: a) Functional Testing b) Regression Testing c) GUI Testing d) Usability Testing e) Security Testing f) Compatibility Testing g) Recovery Testing h) Reliability testing Etc… Drawbacks of Manual Testing (i)Time consuming. (ii) More resources required. (iii)Human Errors (iv)Repetition of the Task is not much (v)Tiredness (vi)Simultaneous auctions are not possible (Parallel) Test Automation: Testing Software using any Automation tools is called Test Automation Advantages of Test Automation:

a) Fast: Tools are faster in execution than human users b) Reliable: Tools are reliable in complex calculations and tasks c) Reusable: we can reuse Automated Tests at any number of times d) Repeatable: we can repeat same operations for required number of times e) Programmable: we can use flow control statements for applying logic f) Comprehensive: we can execute test batches without human interaction also Test Automation can be used in below areas of Testing: a) Functional & Regression Testing b) Load/Stress/Performance Testing c) Security Testing d) Unit Testing Drawbacks of Automation Testing 1) It is expensive 2) We cannot automate all areas. 3) Lack of expertise. 4) It has some limitations (It cannot test everything) which Software Testing should be automated? Tests that need to be execute of every build of the application (Sanity Testing) Tests that use multiple data values (Retesting / Data Drives Testing) Tests that required data from application intimates (G.U.I. Attributes) Load and Stress Testing Which Software Testing should not be automated? Usability testing one time testing Quick looks Tests or A.S.A.P (As soon as possible) Testing Ad-hoc testing / Random Testing Customers requirement are frequently changing. Types of Test tool: ------------------Business: ----------------a) Vendor tools Ex: HP- WinRunner, LoadRunner, QTP, QC

IBM-Rational Robot, ,RFT, RPT, QA Director Borland-SilkTest, Silk Performer etc.. b) Open Source Tools: Ex: Selenium, Jmeter, QAWebLoad, Bugzilla etc... c) In-house tools: Technical: ----------------a) Functional & Regression Test Tools: Ex:WinRunner, QTP, Rational Robot, ,RFT, SilkTest,Selenium etc.. b) Performence/load/stress test tools Ex: LoadRunner, RPT, Silk Performer,Jmeter, QAWebLoad etc... c) Test Management Tools: Ex: QC, QA Director Etc... d) Defect Management tools e) Unit Test tools (Ex: JUnit) Key Elements of QTP Tool Window

Key Elements of QTP Tool Window:
1) Test Pane: It is programming interface of QTP, used for creating, editing, viewing and deleting test scripts. Test: It is a set of statements or set of one or more actions. (It is a local concept) Action: It is a set of Statements. (It is a local concept) Statement: A minimal executable unit. Statements may have keywords. (Keyword such as function, method, statement etc). It is a global concept.

Test pane has 2 views. Expert view- Test in VB script format. Key word view- Test in Icon based GUI format. Note1: Here in test pane Test is same but views are different, if you perform any modifications in one view those automatically reflects in another view. Note 2: Technical users use expert view and business user use key word view. Note 3: User can customize Test pane view options. Navigation: Tools Menu> view options> we can use font size and colors etc. 2) Active Screen It has an optional element of QTP, it takes snap shots of every statement that user performed action or operation on AUT. It can be used for understanding and editing the test easily. Navigation: View menu>active screen (for launching and closing)

Configuring Active Screen: view>options>active screen tab>increase /Decrease capture level, apply and okay. Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP. 3) Data Table It has an integrated spread sheet (Excel like), used for Data driven testing. Navigation: View menu>Data table (for launching and closing)

Data driven Testing: Testing the same task(S) or same operation with multiple sets of test data. It can be used in two ways. 1. Enter test data directly into Data Table and use. 2. Importing data from external files (Flat files, excel sheets, etc) and Data bases (MS access, Sql Server, oracle, etc.) It has two types of sheets. 1). Global Sheet- for entire Test /used for all actions in the Test. 2). Action Sheets- for specific Action only. Data table available in 2 ways: 1). Design time data table. (Attached with every test) 2). Run time data table. (Available in result window) Run time is a carbon copy of design time data table. QTP has Data table methods for performing operations on data table. 4) Debug Viewer

It is used for locating and rectifying or fixing errors. It can be used for debugging the tests by step-by-step execution. We use Step into, Step over and Step out commands for debugging. (debug commands) Navigation: View menu>debug viewer (for launching and closing)

Through Debug viewer user can watch variables and change values of variables temporarily. 5) Missing Resources It can be used for showing missing resources that attached to current test such as (Recovery Scenarios, Library files etc). Navigation: View menu >missing resources (for launching and closing) 6) Information This pane shows syntax errors automatically during saving the test. Navigation: view menu> information

7) QTP Commands QTP Commands are available in 3 ways. 1). Menu options 2). Tool Bar options 3). Short cut keys (for Some important operations only)

QTP Tool Window Menus

File menu: Through file menu user can create, save tests, open existing tests, export tests in zip format.

Edit Menu: It provides editing options and renaming, deleting and splitting actions. View menu: Through this menu we can launch and close, active screen, Data Table, Debug viewer, information, missing resources etc. Insert Menu: Through this menu user can inserting check points, out put values, synchronizing points. In this menu step generator available, using this user can generate recordable and nonrecordable scripts. Through insert menu user can insert VB Script conditional and loop statements and transaction points (Start and End). Through insert menu user can create new actions, call existing actions and copy existing actions. Automation Menu: This menu provides Record, Run options and Run setting options Through this menu we can start normal recording, analog recording and Low level recording. Through this menu we can stop recoding, running and also we run tests. Resources Menu: This menu provides object repository and recovery scenarios options. Through this menu we can create /modify/delete objects information and we can associate repositories. Through this menu we can create, modify and delete recovery scenarios. Debug Menu: This menu provides debug commands for step by step execution. Through this menu we can insert/remove/break points.

Tools Menu: This menu provides Tools settings option, view options and object identification configuration. Through this menu we can set tool options as well as test pane view options. In this menu object spy option available, through this we can get object’s information.(Properties and values) In this menu Virtual object option available; through this option we can create virtual objects. Window Menu: This menu provides QTP tool window style settings. Help Menu: This menu provides QTP help as well as VB Script help. Through this menu we can contact technical support people and we can send feedback. Through this menu we can check for updates and download or install directly. QTP Test Process 7 Stages of QTP Testing Process 1) Planning o Analyzing the AUT o Automation Test Plan Generation o Automation Framework Implementation o Generating/Selecting Test cases for Automation o Collecting Test Data o QTP Tool Settings Configuration 2) Generating Tests o Recording o Keyword driven methodology o Descriptive Programming 3) Enhancing Tests o Inserting Checkpoints o Inserting Output values o Adding Comments

o Synchronization o Parameterization o Inserting Flow Control Statements o Calling User defined functions and/or Reusable Actions o Generating Steps though Step Generator o Inserting Transaction Points o Regular Expressions 4) Debugging Tests o Debug Commands & Break Points o Step by step execution o Watching Variables o Changing values of variables 5) Running Tests o Normal Execution o Batch Execution o Through AOM Scripting o Tests Running through framework o Scheduled Execution 6) Analyzing Results o QTP Result window o Defining our own Results o Exporting Results o Deleting Results 7) Reporting Defects o Manual Defect Reporting o Tool based Defect Reporting o Working with Quality Center ----------------------------------------------------------Types of Statements in QTP Test / Test Script i) Declarations (Variables and constants)

Dim x, y, z Const City, Price ii) Object calls Ex1: Dialog("Login").WinEdit("Agent Name:").Set "gcreddy" Ex2: Browser("Google").Page("Google").Link("Gmail").Click iii) Comments iv) Flow Control Statements (Conditional & Loop) Ex:) If Total=Tickets*Price Then Msgbox "Test Passed" Else Msgbox "Test Failed" End If v) Function / Action calls Ex: Call Login("gcreddy","mercury") vi) Utility Statements Ex1: SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" **It launche the Application Ex2: SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","http://www.icicibank.com/" vii) VB script other statements Examples: Option Explicit Wait (14) Recording Tests Recording and Running a) Test Recording Process

It is a Process of Recording user operations on AUT (Application Under Test). During Recording QTP Creates steps in Keyword view, and generates them in a script in the Expert view. Simultaneously it adds Objects information into Object Repository. b) Running /Execution Process During Running QTP reads statements one by one and gets Object Information from the Object Repository, based on that Information performs operations on AUT. c) Recording Modes QTP has 3 Recording Modes to generate Tests / Test Scripts i) Normal Recording It records User Mouse and Keyboard operations on AUT with respect to objects, but unable to record continuous mouse operations like Digital Signatures, graphs, paints etc. During recording QTP generates VbScript statements in Test Pane, Simultaneously it stores objects information into object repository. Navigation: Automation>Record Or Select Record option on automation toolbar Or Use short cut key (F3) Steps for preparing a Test (through Recording): 1.Put AUT in base state 2.Select Record Option 3.It shows Record and Run Settings, Select type of Environment (Windows or Web) 4.Select Record Option (It shows two Options : 1.Record and Run Test on any open window based applications 2.Record and Run only on) If we select first option it records on any opened application on Desktop. If we select Second option, it asks for the path of the AUT, After Providing the path it records only on that particular application.)

5.Click OK 6.Perform actions on AUT 7.Stop recording. 8.Save the Test ii) Analog Recording: It records the exact mouse and keyboard operations. We can use this mode for recording continuous mouse operations. It is not useful for recording normal operations why because it does not generate steps for each operation, generates total user actions in a Track File. The Track file is not editable. Navigation: 1.Keep tool under recording mode 2.Automation >Analog Recording OR Use Short cut Key (Shift + ALT+F3) Steps for preparing a Test (through Analog Recording): 1.Launch AUT (or we can launch AUT through QTP) 2.Select Record option 3.Automation>Analog Recording 4.Analog Recording Settings Dialog box opens (In this Dialog box two options available. 1.Record relative to the screen 2.Record relative to the following window) (If we select first option QTP records User operations with respect to Desktop coordinates. If we select Second option, we have to show the window (AUT), after showing the Window it records with respect to that window co-ordinates.) 5.Select any one option in the dialog box and click Start Analog record. 6.It records User actions 7.Stop Recording

iii) Low Level Recording It records some operations on Non-supported environments apart from Normal operations. This mode records at the object level and records all run time objects as window or winobject Test objects. Use Low Level Recording for recording in an environment not recognized by QTP. Navigation: 1.Keep tool under recording mode 2.Automation >Low Level Recording Steps for preparing a Test (through Low Level Recording): 1)Launch AUT (or we can launch AUT through QTP) 2)Select Record option 3)Automation> Low Level Recording 4)Perform options on AUT 5)Stop Recording 6)Save the Test d) Disadvantages of Recording • It occupies a lot of memory space(due to duplicate objects), So QTP performance will be reduced • No Centralized Maintenance mechanism , So Modifications are very difficult • User may not have command on the Recorded script, So locating errors is difficult • Recorded scripts are QTP internal files, they may corrupt. e) Advantages of Recording/ Where Applicable • It is used for Analyzing the AUT in the initial stage to find out weather the QTP tool is Recognizing all of our Application Objects or not • It is easy to create Tests / Test Scripts

•It is used for frequently changing UI (User Interface) • It takes less time to create Tests Keyword-Driven Methodology By creating our tests with a keyword-driven methodology in mind, our tests become more modular, focusing on the operations to test using both QuickTest built-in keywords and your own user-defined keywords. Additionally, because it is possible to add objects to the object repository before they exist in an application, it is possible to begin preparing our automated keyword-driven tests even before a software build containing the new objects is available. Setting up Object Repositories In this step, we build one or more object repositories and ensure that all objects have clear names that follow any predetermined naming conventions defined by our organization. We can create object repositories using QuickTest functionality to recognize and learn the objects in your application, or we can manually define objects. By creating and populating shared object repositories that can be associated with multiple actions, we can use the same object repository in multiple tests. Add (learn) objects from our application. We instruct QuickTest to learn the objects in our application according to filters that we define. Ensure that objects in the object repository have names that are easy for application testers to recognize and that follow any established object naming guidelines. This helps make both test creation and maintenance easier over time. Configuring QuickTest According to our Testing Needs After we set up the test automation infrastructure, we need to configure QuickTest to use this infrastructure:

Define your global testing preferences. We need to specify configuration settings that affect how we create and run tests in general—these settings are not test-specific. Building our Tests We can create tests that are as simple or complex as needed. In general, it is best to create tests and actions that check just one or a few simple functions or complete a transaction rather than creating long tests and actions that perform several complex tasks or that perform many tasks. We may perform the following tasks when creating tests and test steps: Create new tests, if needed. To do so, select File > New > Test. Create the required actions. Associate our object repositories with the relevant actions This enables us to insert steps that perform operations on those objects. Associate our function libraries with the relevant tests. This enables us to use our special keywords in any of the associated tests. Test Object Model The test object model is a large set of object types or classes that QuickTest uses to represent the objects in your application. Each test object class has a list of identification properties that QuickTest can learn about the object, a sub-set of these properties that can uniquely identify objects of that class, and a set of relevant operations that QuickTest can perform on the object. A test object is an object that QuickTest creates in the test to represent the actual object in your application. QuickTest stores information on the object that will help it identify and check the object during the run session. A run-time object is the actual object in your application on which methods are performed during the run session.

When QuickTest learns an object in our application, it adds the corresponding test object to an object repository, which is a storehouse for objects. we can add test objects to an object repository in several ways. When you add an object to an object repository, QuickTest: • Identifies the QuickTest test object class that represents the learned object and creates the appropriate test object. • Reads the current value of the object's properties in your application and stores the list of identification properties and values with the test object. • Chooses a unique name for the test object, generally using the value of one of its prominent properties. Test Object and Native Properties and Operations The identification property set for each test object is created and maintained by QuickTest. The native property set for each run-time object is created and maintained by the object creator (for example, Microsoft for Microsoft Internet Explorer objects, Netscape for Netscape Browser objects, the product developer for ActiveX objects, and so on). Similarly, a test object operation is a method or property that QuickTest recognizes as applicable to a particular test object class. For example, the Click method is applicable to a WebButton test object. As you add steps to your test, you specify which operation to perform on each test object. If you record steps, QuickTest records the relevant operation as it is performed on an object. During a run session, QuickTest performs the specified test object operation on the runtime object. Native operations are the methods of the object in your application as defined by the object creator. Property values of objects in your application may change dynamically each time your application opens, or based on certain conditions. You may need to modify the identification property values to match the native property values. You can modify identification properties manually while designing your test, or use 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. For more information on modifying object properties, see Managing Test Objects in Object Repositories. Understanding and Using Regular Expressions.

You can view or modify the identification property values that are stored with your test in the Object Properties or Object Repository dialog box. For more information, see Specifying or Modifying Property Values. We can view the current identification property values of any object on your desktop using the Properties tab of the Object Spy. For more information, see Viewing Object Properties and Operations Using the Object Spy. We can view the syntax of the test object operations as well as the native operations of any object on your desktop using the Operations tab of the Object Spy. For more information, see Viewing Object Properties and Operations Using the Object Spy. We can retrieve or modify property values of the test object during the run session by adding GetTOProperty and SetTOProperty statements in the Keyword View or Expert View. We can retrieve property values from the run-time object during the run session by adding GetROProperty statements. For more information, see Retrieving and Setting Identification Property Values. If the available test object operations and identification properties for a test object do not provide the functionality you need, you can access the internal operations and properties of the run-time object using the Object property. You can also use the attribute object property to identify Web objects in your application according to userdefined properties. For information, see Accessing Native Properties and Operations. Understanding Object Repository Types Objects can be stored in two types of object repositories—a shared object repository and a local object repository. A shared object repository stores objects in a file that can be accessed by multiple tests (in read-only mode). A local object repository stores objects in a file that is associated with one specific action, so that only that action can access the stored objects. When you plan and create tests, you must consider how you want to store the objects in your tests. You can store the objects for each action in its corresponding local object repository, or you can store the objects in your tests in one or more shared object repositories. By storing objects in shared object repositories and associating these repositories with your actions, you enable multiple actions to use the objects. For each action, you can use a combination of objects from your local and shared object repositories, according to your needs. You can also transfer local objects to a shared object repository, if required. This reduces maintenance and enhances the reusability of your tests because it enables you to maintain the objects in a single, shared location

instead of multiple locations. For more information, see Deciding Whether to Use Local or Shared Object Repositories. If you are new to using QuickTest, you may want to use local object repositories. In this way, you can record and run tests without creating, choosing, or modifying shared object repositories because all objects are automatically saved in a local object repository that can be accessed by its corresponding action. If you modify an object in the local object repository, your changes do not have any effect on any other action or any other test (except tests that call the action, as described in Inserting Calls to Existing Actions). If you are familiar with testing, it is probably most efficient to save objects in a shared object repository. In this way, you can use the same shared object repository for multiple actions—if the actions include the same objects. Object information that applies to many actions is kept in one central location. When the objects in your application change, you can update them in one location for all the actions that use this shared object repository. If an object with the same name is located in both the local object repository and in a shared object repository associated with the same action, the action uses the local object definition. If an object with the same name is located in more than one shared object repository associated with the same action, the object definition is used from the first occurrence of the object, according to the order in which the shared object repositories are associated with the action. For more information on associating shared object repositories, see Associating Object Repositories with Actions. Local objects are saved locally with the action, and can be accessed only from that action. When using a shared object repository, you can use the same object repository for multiple actions. You can also use multiple object repositories for each action. When you open and work with an existing test, it always uses the object repositories that are specified in the Associated Repositories tab of the Action Properties dialog box or in the Associate Repositories dialog box. Shared object repositories are read-only when accessed from tests; you edit them using the Object Repository Manager. Object Repository: It is a storage place of QTP where objects information can be stored and it also acts as interface between the Test script and the AUT in order to identify the objects during execution. Object: Object is something, which has structure and properties. Software objects:

We call Windows, Web Pages, Buttons, Edit boxes, Check boxes etc.. as software objects. Types of Object in QTP: There are four types of object available in QTP. 1. Run time objects 2. Test objects 3. Utility objects 4. Automation objects/User defined objects. Run time objects: The objects present in the AUT. Ex: Buttons, Links, etc… Test Objects: References of Run time objects. Ex: WinEdit, WinButton, WebButton, Link, etc… Note: Test objects names vary from one environment to another. Utility objects They are QTP reserved objects used for Testing and Result reporting. Ex: 1. SystemUtil for launching/closing the application. 2. Reporter for defining results. 3. Services for inserting transaction points 4. Environment for using environment variables Automation objects/User defined objects User can create objects; those can be used for performing specific operations. Ex: Creating objects in filesystemobject class, adodb.connection class, dictionary object class, Excel. Application class etc. There are two types of repository available in QTP. 1. Local repository (.MTR extension) 2. Shared repository(.TSR extension)

Local Repository: QTP creates a Local Repository for every Action automatically during Recording. That cannot be shared among tests. User can add some more objects to Local repository User can perform rename, delete operations on local repository. As it is QTP internal file user no need to save modifications.

Shared Repository: User (Test Engineer) creates the Shared Repository by adding objects. That can be shared among number of tests. Using this method user can perform modifications on objects easily. Operations on Object Repository Adding objects a. Local Repository: Navigation: open Local Repository (Resource Menu > Object Repository) objects>Add objects to Local> Show the Object>Click Ok (No need to save separately, it saves automatically) B. Shared Repository:

Navigation: Resource menu>object repository manager>object>Add objects>show the window/object>click ok o Selected object only o Default object types o All objects types o Selected object types (If we select first option it stores Selected objects only, if we select second option it stores all default objects, if we select third option it stores All objects including static objects, if we select fourth option, we have to select object classes then it stores that class objects, we can select more than one class also.) Renaming Objects a. Local Repository: Resources > object repository >select object and right click >choose rename option >modify the name>release the mouse.>close repository b. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose rename option>modify the name > release mouse>save the file & close repository manager. Deleting Objects a. Local Repository: Resources > object repository >select object and right click >choose delete option >confirm deletion>. >close repository b. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose delete option>confirm the deletion >save the file & close repository manager. Associating Object Repositories to an Action/Test

Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok Merging Repositories Resources > object repository manager>tools>object repository merge tool >browse path of the first repository> browse path of the second repository>click ok>click close>save the merged repository>close the repository manager. Note: After merging also, source repository files will be available, if we do not want source files we can delete. Defining New Test Objects Navigation: Object>Define new test object >Select Environment>Select Class of the object>Enter name of the object>Click Add>click close>Select object >select property name>enter value (like this select one by one properties and enter values)>save Note: This feature can be used for preparing tests before the AUT is ready. Spying Objects For getting objects information, (Test objects names, property & Values) QTP is providing a feature called Object Spy, using this we can get objects information. Navigation>Tools>object spy>take hand icon & Show the object>get information (Object Spy shows the specific objects all available properties with their values) Note: As Object spy is an important feature, it can be available in 3 Areas.(1. In tools Menu 2. In local repository 3. In Repository manager) View Options Locate in Repository This feature can be used for identifying objects from application to repository. Navigation: View>Locate in repository >show the object>click Ok>it locates specified object in the repository.

Highlight in Application This feature can be used for identifying objects from repository to application. Navigation: Select object in the repository >view>highlight in application>it highlights specified objects in the application. Exporting Repository to an XML file We can export our repository file to an xml file. Navigation: File >export Test objects to XML Enter the file name and Save with xml extension. Importing Repository from XML file. We can import XML file to our repository. Navigation: File>import from XML >browse path of the XML file >it loads objects. Note: The purpose of this feature is Editing objects information outside of the QTP Navigation: Resource menu>object repository (Short cut key Ctrl+R) Object Identification Configuration Overview: Generally for every object 20-25 properties information available, qtp recognizes object using 2 0r 3 important properties. Qtp has default object identification configuration for every environment, if we feel that config is not sufficient for recognizing objects in our application, we can configure some more Object Identification Types a) Normal identification 1) Mandatory properties 2) Assistive properties

b) Smart identification 1) base filter properties 2) optional filter properties c) Ordinal identifier 1) location 2) index 3) creation time(only for web) QTP learns information in the following in case of normal identification: First of all the qtp learns all the mandatory properties at a time and thinks whether these properties sufficient to identify the object uniquely. if it feels sufficient then it stops learning otherwise, It learns first assistive property and once again stops and thinks, like this qtp learns one by one. At the end of assistive properties list also if it feels not satisfied and it finally goes to Ordinal Identifier.

QTP learns information in the following in case of Smart Identification: Smart identification is an optional feature, if we feel normal identification is not sufficient for any object, and then we configure Smart Identification for that object, in order to avoid Ordinal Identifier. After normal identification if qtp feels not satisfied then it goes to smart identification. in smart identification 2 types of properties available, first qtp learns all base filter properties at a time and thinks whether these properties are sufficient for identifying the object uniquely. If it feels sufficient, then it stops learning otherwise it goes Optional Filter Properties and learns one by one. Still it feels not satisfied finally it goes to Ordinal Identifier. Ordinal identifiers: There are 3 types of ordinal identifiers available

1) Location: is based on object location in the AUT ,location starts from zero. 2) index: it is based on sequence of the programs, index starts from zero 3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2 like numbers. Tool Settings Globalization: As QTP is a I-tier(Stand-alone) application,making Tool settings globally is not possible. For making tool settings global, QTP is providing a special feature called "Generate Script". STEPS: 1) Settings available in 3 areas. a) File->Settings b) Tools->Options c) Tools->Object Identification 2) Perform required settings and generate Scripts 3) Share Script files to team members and ask them to execute those scripts. NOTE: After executing these scripts all team members can get same settings. QTP Methods Activate: It activates dialog boxes/Windows Syntax: Object hierarchy. Activate Ex: Dialog(“Login”).Activate Window(“Flight Reservation”).Activate Click Method: It clicks on an object (Buttons) Syntax: Object hierarchy. Click Ex: Dialog(“Login”).Winbutton(“ok”).click

Close Method: It closes the window,Dialog box, Browser window etc. Syntax: Object hierarchy. Close Ex: Window(“Flight Reservation”).Close Browser(“Browser”).Close Dblclick: It Double clicks the object. Set Method: It can be used in three ways. a. For setting the value of an edit box Syntax: Object Hierarchy. SET “Value” Ex: Dialog (“Login”).WinEdit(“Agent Name”).Set “asdf” b. Selecting a Radio Button Syntax: Object Hierarchy. Set Ex: Window("Flight Reservation").WinRadioButton("Business").Set c. Selecting/Deselecting check boxes Syntax:object Hierarchy.Set “ON/off” Ex: Window ("Flight Reservation"). Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Select Method: It is used for selecting an item from a combo box or list box. Syntax: Object hierarchy.select “item” Ex: Window("Flight Reservation").WinComboBox("Fly From:").Select "London" Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "12572 GetVisibletext: It returns Text from the specified area. Syntax: Variable =object hierarchy.getvisibletext Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleText msgbox x GetRoproperty: It returns current object property value. It can be used for getting any object’s, any property value. Syntax: Variable = object hierarchy.getroproperty (“property name”) Ex: x=Window("Flight Reservation").WinEdit("Tickets:").GetROProperty ("width")

msgbox x Navigate Method: It opens a specified URL in the Browser. Syntax: object hierarchy.navigate “URL” Ex: Browser("Yahoo!").Navigate http://www.google.co.in/ Getitemscount: It returns number of items in a combobox. Syntax: Variable=object hierarchy.getitemscount Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount msgbox x Getcontent: It returns all items from a combobox. Syntax: variable=object hierarchy.GetContent Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetContent msgbox x Exist property: It checks whether the object is available or not. Syntax: Object hierarchy.exist(time in seconds) Ex: Window("Flight Reservation").Exist(5) QTP Data Table Methods (1) Add Sheet: We can use this method to “add” one new sheet to the run time data table. Syntax: DataTable.AddSheet "sheet name" Ex: DataTable.AddSheet "gcreddy" (2) Delete Sheet: We can use this method to “delete” one specified sheet from the Run Time Data table.

Syntax: datatable.DeleteSheet (Sheet_ID) Ex: datatable.DeleteSheet (3)

(3) GetSheetCount

We can use this method to count number of sheets in the run time data table.

Syntax: datatable.GetSheetCount msgbox datatable.GetSheetCount (4) GetRowCount

We can use this method to count number of rows in the 1st sheet (longest column) of the Run time data table.

Syntax: datatable.GetRowCount

Ex: msgbox datatable.GetRowCount (5) GetSheet

We can use this method to return a specified sheet from the Run Time data table.

Syntax: datatable.GetSheet(SheetID)

Ex: msgbox datatable. GetSheet(1).GetRowCount

(6) Value We can use this method to set or get value of cell in the specified parameter and the current row of the Rum time data table.

To set data

Syntax: datatable.Value(Parameter_Name, Sheet_Name) = Value / variable Or

datatable(Parameter_Name, Sheet_Name) = Value / variable

To get data Syntax: Variable = datatable.Value(Parameter_Name, Sheet_Name) Or Variable = datatable(Parameter_Name, Sheet_Name)

Ex: Option explicit Dim a, b, c

a=datatable.Value (1,1) b=datatable.Value (2,1) c=cint(a)+cint(b) datatable.Value (3,1) = c Note: Default property of Datatable is value (7) SetCurrentRow

We can use this method to take a specified row as current row in the Run Time Datatable (By default it is 1st Row of 1st Sheet) Syntax: datatable.SetCurrentRow(Row_Number) g="gcreddy" datatable.SetCurrentRow (3) datatable.Value (1,1) = g

(8) SetNextRow

We can use this method to take the row after the current Row as New Current Row in the Run time data table.

Syntax: datatable.SetNextRow

Ex: g="gcreddy" datatable.SetCurrentRow (3) datatable.SetNextRow datatable.Value (1,1) = g

(9) SetPrevRow We can use this method to take the row before the current Row as New Current Row in the Run time data table.

Syntax: datatable.SetPrevRow

Ex: g="gcreddy"

datatable.SetCurrentRow (3) datatable.SetPrevRow datatable.Value (1,1) = s

(10) Import We can use this method to import Microsoft Excel File to the Runtime Data Table (Including all sheets)

Syntax: datatable.Import “Path of File” Ex: datatable.Import “F:\Inputdata.xls” 11) ImportSheet We can use this method to import a specified sheet of Microsoft Excel Sheet to the Runtime Data table.

Syntax: datatable.ImportSheet “Path of File”, “Source Sheet”, “Destination Sheet” Ex: datatable.ImportSheet “E:\gcreddy.xls”,3,1

(12) Export

We can use this method to export a copy of Run Time Data table to another location (Including all sheets)

Syntax: datatable.Export “Path of File”

Ex: datatable.Export “F:\gcreddy.xls”

13) ExportSheet

We can use this method to export a copy specified sheet of Run Time Data table to the existing or new Excel File. Syntax: datatable.ExportSheet “Path of File”, “Sheet Name / Source Sheet”

Ex: datatable.ExportSheet “F:\gcreddy.xls”, 2 ********************** Data Driven Testing for Login Operation using Data Table methods Datatable.AddSheet "Login" Datatable.ImportSheet "C:\Documents and Settings\gcr\Desktop\gcreddy.xls",1,3 Rows_count=Datatable.GetSheet(3).GetRowCount For i= 1 to Rows_count Datatable.SetCurrentRow(i) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate

Dialog("Login").WinEdit("Agent Name:").Set Datatable("Agent",3) Dialog("Login").WinEdit("Password:").Set Datatable("Pwd",3) Dialog("Login").WinButton("OK").Click If window("Flight Reservation").exist(10) Then Login="Login Operation Successful" Datatable("Result",3)=Login Reporter.ReportEvent micPass,"res","Passed" else Reporter.ReportEvent micFail,"res","Failed" Login="Login Operation Failed" Datatable("Result",3)=Login Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click End If If Window("Flight Reservation").Exist(3)Then Window("Flight Reservation").Close End if Next Descriptive Programming Entering / Providing objects information directly into the test script is called Descriptive Programming. In this method of script creation, we no need to have Object Repositories. Advantages: a) Descriptive Programming based Test scripts are faster in execution than Repository based Test scripts. b) Scripts are portable (we can run these scripts from any machine easily) c) Maintenance is easy (less amount of resources)

d) We can start Test Execution process even though Application is not ready. Descriptive programming is basically 2 types. 1. Static Programming 2. Dynamic Programming Static Programming In this style of script generation, we provide objects information directly into the script. Example: 1) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" 2) dialog("text:=Login").Activate 3) dialog("text:=Login").Winedit("attached text:=Agent Name:").Set "gcreddy" 4) dialog("text:=Login").Winedit("attached text:=Password:").Set "mercury" 5) dialog("text:=Login").Winbutton("text:=OK","width:=60").Click Note: 1. Dialog, WinEdit and WinButton – Test Objects 2. text, attached text - Property names 3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the Object 4. Activate, Set, Setsecure, Click - Methods Note2: If we feel one property information is not sufficient for recognizing the object uniquely, then we can provide more properties information by separating with commas. Note 3: If we want to get objects information (Test objects, properties and values), we can use object spy feature. This feature is available in Tools Menu, in local repository and in repository manager. Example 2: SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","","C:\Program Files\Internet Explorer","open" Browser("title:=Google").Page("title:=Google").Sync Browser("title:=Google").Navigate "http://www.icicibank.com/"

------------------------------------------------------------------If we want maintain ‘Objects information’ in centralized location then we can use Constants. Steps: Creating Constants: Const Login="text:=Login", Agent="attached text:=Agent Name:" Const Pwd ="attached text:=Password:", Ok="text:=OK" Note: we can declare no of Constants in a line by separating with Camas (,), if we take other line then we have to use Const Statement again. Creating a Library file Place Constants in Notepad and save as .vbs file Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon-> Browse path of the Library file->Click Apply and click Ok buttons Otherwise, we can load the library file during run-time Syntax: ExecuteFile “Path of the Library file(.vbs)” After that create the Test Script using Constants Creating the Test Script using Constants: Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog(Login).Activate Dialog(Login).Winedit(Agent).Set "asdf" Dialog(Login).Winedit(Pwd").Set "mercury" Dialog(Login).Winbutton(Ok).Click

Advantages: If we maintain Object Information in the centralized location, then we can handle modifications easily. ------------------------------------------------------------------Dynamic Programming In this style of script generation, first we create description objects, provide properties information and use description objects in the test script. Creating Properties Collection Objects Set oLogin=description.Create Set oAgent=description.Create Set oPassword=description.Create Set oOk=description.Create Entering Properties Information into Objects oLogin("text").value="Login" oLogin("width").value=320 oLogin("height").value=204 oAgent("attached text").value="Agent Name:" oPassword("attached text").value="Password:" oOk("text").value="OK" Generating Tests using Properties collection Objects Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog(oLogin).Activate Dialog(oLogin).Winedit(oAgent).Set "gcreddy" Dialog(oLogin).Winedit(oPassword).Set "mercury" Dialog(oLogin).Winbutton(oOK).Click Note1: Create Description objects and put into one library file, by associating that library file, we can generate tests.

Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy. -----------------------------------------------------Examples: Handling similar/Duplicate Objects using Index Property SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE" Browser("name:=Google").Page("title:=Google").Sync Browser("name:=Google").Navigate http://www.jjperfumes.com/ Browser("name:=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online").page("title:=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online").Link("innertext:=Register","index:=0").Click Inserting Checkpoints Check point is a verification point, it takes expected result from the user and compares with actual results during execution and provides test results. There are 11 Checkpoints available in QTP: 1. 2. 3. 4. 5. 6. 7. 8. 9. Standard check point Text check point Text area check point Bit map check point Data base check point Accessibility check point XML Check point (from Application) XML Check point (from Resource) Page check point 10. Image checkpoint 11. Table checkpoint

Note 1: From 6 to 11 checkpoints are only for Web. Note 2: From 9 to 11 checkpoints are hidden checkpoints, we can insert these checkpoints through standard checkpoint.

1. Standard Checkpoint: It checks object property values. We can use this checkpoint for checking any property value. Navigation for inserting standard checkpoint Keep tool under recording mode > place cursor in desired location > Insert > check point > Standard checkpoint > Show the object > click okay > select property and enter expected results & click Ok and stop Recording. Navigation for Editing standard checkpoint Select Checkpoint statement and right click > choose checkpoint properties option > modify the value > click Ok. Navigation for Deleting standard checkpoint: Select Checkpoint statements and right click > choose delete option. Inserting Standard check points through active screen: View > Active Screen >place cursor in desired location >Place mouse pointer on active screen & right click> choose insert standard checkpoint option > click ok > enter expected result > click ok Note: Inserting Standard check points through keyword view same as in expert view. Note: We can insert standard checkpoints in 3 ways. a. b. c. Through expert view, Through keyword view, Through Active screen.

2) Text Checkpoint: It Checks object’s text property value in different ways. Navigation: Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint > Show the object > click ok > Select options (Match case; ignore spaces, exact match, text not displayed.) We can select one or more options > click ok & stop Recording. 3) Text Area Checkpoint: It checks the text area present in the application. Navigation: Keep tool under Recording mode > Insert menu> Checkpoint > Text area checkpoint > Mark the area of text > select one or more options (Match case, ignore spaces, exact match, text not displayed.) Click ok and stop recording. 4. Bitmap checkpoint: It compares bitmaps; we can compare complete bitmaps as well as part of the bitmaps. Navigation: Keep tool under Recording mode > Insert menu > Checkpoint > Bitmap checkpoint > show the Bitmap >click ok >select “check only selected area” option if we want to compare part of the bitmap > click ok >stop recording. 5. Database checkpoint: It checks Content of the back end Database. Navigation:

Insert > checkpoint > Database checkpoint >choose “specify SQL statement manually” option >click next > click create > select machine data source > Select DSN (QT_flight32) > click ok > enter SQL statement (select * from orders) > finish > click ok. Note: here we do not need to put tool under Recording mode and we do not need AUT since data is from backend. 6. Accessibility check point: It checks whether the webpage in our web application is developed according to W3C (World Wide Web consortium) Rules and Regulations or not. It is a configurable checkpoint, according to our requirements, we can customize. Configuring accessibility checkpoint: Tools menu> options >web > advanced > check/uncheck items > click apply > click ok Invigilation: Keep tool under recording mode with web environment >insert>checkpoint>accessibility checkpoint>show the webpage>click ok>click ok>stop recording. Result Criteria: a) If item is available but not according to W3C rules then fail. b) c) If an item is available, according to W3C rules then Pass. If an item is not available then result would be pass 7. XML Check point (from Application) It checks content of the XML file. Navigation: Keep tool under Recording mode in web environment > insert menu > checkpoint (from application)> show the xml pages >click ok > stop Recording. 8. XML Check point (from Resource) It checks content of the XML file.

Navigation: Insert menu > checkpoint >xml checkpoint (from resource) > browse path of the XML File > click ok > click ok. Note: 1. If XML file is an individual and path available, and then we can go for inserting xml checkpoint from resource. Note: 2. If XML file is part of web application, separate path is not available then we can choose inserting XML checkpoints from application. 9. Page checkpoint: It checks number of Links, Images and Loading time in a web page. It is a hidden checkpoint; we can insert this through standard checkpoint. Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint > Standard checkpoint >show the web page > click ok > click ok > stop recording. 10. Image checkpoint: It checks Image property values. Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint >standard checkpoint > show the image > select image > click ok > click ok >stop recording. 11. Table checkpoint: It checks content of the web tables. Navigation: Keep tool under Recording mode under web environment > Insert menu > checkpoint > standard checkpoint >show the web table > click ok >stop recording. Inserting Output Values It is a step in which one or more values are captured during test execution.

The values can later be used as input at a different point in the run session or we can use as input for another test. It is stored in run time data table; it is located in QTP result window and can be retrieved later. Types of Output Values: 1. 2. 3. 4. 5. 6. Standard output value Text output value Text area output value Database output value XML output value (From Application) XML output value (From Resource)

1) Standard output value: We can use standard output values to output the properties values of most objects. Navigation: Keep tool under Recording mode > Insert menu >output value> standard output value > show the object > click ok > select property > modify the column name (if required) > click ok >click ok >stop recording. 2) Text output value: We can use Text output values to output text strings displayed in an application. When creating a text output value we can output a part of the objects text and we can also specify text before and after options. Navigation: Keep tool under recording mode> Insert menu> output value > text output value > show the text >select one of the option(output text/text before/text after) > click modify if you want to change the column name > click ok > click ok.> check in runtime table after running it.

3) Text Area output value: We can use text area output values to output text strings displayed within a defined area of the screen. Navigation: Keep tool under recording mode > insert menu >output value > text area output value >Mark the text area >click modify the column name if necessary > click ok > again click ok > check in run time table after running it.. 4) Database output value: We can use Database output values to output the value of the contents of database cells. Navigation: Insert menu> output value > Database output value> choose specify SQL statements manually >click next >click create >Select Machine Data source > Select Driver (QT_flight32) > click ok > enter SQL statement (select *from orders) > click finish > select data cells > click ok > Run and it will capture and see the results in run time table. 5) XML output value (from application): we can use XML output values to output the values of XML elements in XML documents. Navigation: Keep tool under recording mode with web environment > Insert menu > output value > XML output value from application > Show the XML document > select elements > click ok >stop recording. 6) XML output Value (From Resource): We can use XML output values to output the values of XML elements in XML documents. Navigation: Insert menu >output value> XML output value from resource > browse path of the XML file > click ok > select elements >click ok.

Parameterization Passing parameters, through this we can pass multiple values. We use parameterization in Data Driven Testing. Data Driven Testing: Testing the Same operation with multiple sets of test data. Types of Parameterization: We can parameterize tests in several ways in QTP 1. Through Loop Statements 2. Dynamic Test Data Submission 3. Through Data Table 4. Fetching Test Data directly from External files (Flat files & Spreadsheets) 5. Fetching Test Data directly from Databases (MSAcess, Oracle etc). 6. Getting Test Data from front end objects. 1. Through Loop Statements: We can use loop statements for passing sequential numbers & Logical Numbers. Note: We can’t generate Strings. For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set orderno Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click Next 2.Dynamic Test Data Submission: Through Loop Statements we can give strings also but every time user has to enter data. For x=1 to 3 Agent =inputbox("enter an Agent Name") Password=inputbox("enter a password") invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Agent Name:").Type micTab

Dialog("Login").WinEdit("Password:").SetSecure password Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Next 3. Through Data Table: QTP adds one data table (Spreadsheet) for every test, we can use Data Table for Data Driven Testing. It has 3 types of usage: a. Entering test data directly into data table and use b. Importing test data from external Flat files c. Importing test data from external Spread sheets d. Importing test data from Data bases.

A. Entering test data directly into data table and use.

Steps: Generate the basic test>open data table (View>Data Table)

Click on column header>enter the name of the field (like this we can create number of columns) > Enter Data>connect the data to test

(variable=datatable(“column name”, Sheet id) Example: agent=datatable(“agent”,1) Pass parameters.)

Run the test.

Agent = Datatable("Agent",1) pwd=Datatable ("Password",1) invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure pwd Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close

b. Importing test data from external files:

Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browsw path of the file(it imports data from the flat file)

Connecting Test Data to QTP Test as above and run the test.

c. Importing test data from external Spread sheets:

Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browse path of the excel sheet (it imports data from the excel sheet)

Connecting Test Data to QTP Test as above and run the test.

D. Importing test data from Data bases: Through Data table we can import Test Data from Data bases, but first we have to create /get the DSN(Data source Name)& we have to use SQL Commands.

1. Creating a Test Database: open MS Access (or we can use any other database).

Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension.

Creating Tables: Select Create table in design view>Enter field name(Agent)and Select data type(text) Like this we can create number of fields>save&enter table name.

Entering Data into Tables: Select table>enter the data.

Creating DSN & importing data

Navigation: view>data table>Place mouse pointer on Data table>sheet>import>from database(Database query wizard opens)>choose ‘specify SQL statements manually>click next >click create>click new>select driver type>click next >browse path to store> enter DSN Name>Click Save>click next>click finish>select>browse the database& select>click ok>click ok>select DSN>click ok>enter SQL statement (select *from login)>click finish. Note: DSN Creation is one time activity, by using the DSN we can get data for number of tests. 4. Fetching Test Data directly from Flat files Dim fso, myfile Set fso=createobject("scripting.filesystemobject") Set myfile=fso.opentextfile("d:\trigun.txt",1) myfile.skipline While myfile.atendofline <> true x=myfile.readline S=split(x,"@") SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set s(0) Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure S(1) Dialog("Login").WinEdit("Password:").Type micReturn Window("Flight Reservation").Close Wend Fetching Test Data directly from Excel Sheets Fetching Test Data directly from Databases

Option explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.provider=("microsoft.jet.oledb.4.0") con.open "C:\Documents and Settings\pooja\My Documents\trigun.mdb" rs.open "select * from login",con do until rs.eof=true SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("agent") Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure rs.fields("password") Dialog("Login").WinEdit("Password:").Type micReturn Window("Flight Reservation").Close rs.movenext loop Synchronization It is a process of matching the speeds of both QTP and AUT in order to get proper execution and results.

Where Synchronization is required: During test execution QTP gives instructions one by one with same speed, but AUT takes less time for some operations execution and more time for some operations execution, that time we may not get proper execution and results. In order to get proper results in between QTP & AUT synchronization is required. There are several methods available in QTP for synchronization. 1. Inserting Wait statements. 2. Inserting Synchronization points. 3. Increasing Tool default synchronization time. 4. Sync Method (Only for WEB) 5. Exist Property Inserting Wait Statements:

We can insert wait statements in our test in order to make QTP to wait until AUT completes current operation. Syntax: Wait(time in seconds) Note: If we insert wait statements QTP waits up to maximum time even though operation is completed. Inserting Synchronization points: Place cursor in desired location>keep tool under recording mode>Insert menu>Synchronization point >show the object >click ok>select property name & Value(True)>enter time in Milli seconds>click ok>Stop recording. Note: if we insert Synchronization points, it does not wait up to maximum time, after completion of the current operations, it goes to next step immediately. Syntax: object hierarchy.waitproperty “property name”,value,time in milli seconds. Increasing Tool default synchronization time: Navigation: File>settings>run tab>increase object synchronization time out>apply>ok Note: If we increase QTP tool default time that can be applied for all statements in the test, but QTP does not wait up to maximum time unnecessarily, After completion of one statement execution it goes to next statement immediately. Sync Method: (only for WEB) Waits for the browser to complete current navigation. Syntax: Object Hirearchy.Sync Ex: Browser("Yahoo! Toolbar").Page("Yahoo! Toolbar").Sync Selecting an appropriate Method: 1. Suppose in our test one or more statements only are taking more time for execution then selecting “Inserting synchronization method” is better. 2. Suppose in our test more statements are taking more time for execution then selecting “increasing tool time out” .

3. Above two are local features but wait statement is Vbscript feature, even though some drawbacks are there in using wait statement, it is better to use wait statement in functions. Advantages of Wait Statement: 1) It is a VBScript statement, we can use this globally 2) It is recommended, whenever we want to observe the Test Execution process 3) No object reference required to insert wait statements 4) It is useful to make QTP capture values and screen shots during test execution Inserting Transaction Points QTP is providing a Utility object called Services for measuring transaction time Suppose, we want to measure how much time that one test or part of the test is taking for execution/running, we can measure using these transaction point (Start and End) Syntax: Services.StartTransaction “Transaction Name” Statements -----------Services.EndTransaction “Transaction Name” Note: these options (Start and End Transactions) available in QTP tool Insert menu Example: services.StartTransaction "Login" SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "naga" Dialog("Login").WinEdit("Password:").SetSecure

"4baf50f18b0ae0d5f5425fe760653e96da50bde7" Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Activate services.EndTransaction "Login" Note: We can insert number of transaction points in a test Using Timer Function

‘Timer’ is a VB Script Built-in function, that can be used for measuring transaction time. ST=Timer’ It returns elapsed time since 12:00 AM Mid night in seconds Example: SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "naga" Dialog("Login").WinEdit("Password:").SetSecure "4baf50f18b0ae0d5f5425fe760653e96da50bde7" Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Activate ET=Timer TT=ET-ST msgbox TT

Note: here ST, ET and TT are variables, you can take any variable, I used: ST for Start Transaction ET for End transaction TT for Transaction Time Step Generator (F7) Step Generator is a feature of QTP, Library of Functions, used for generating the Recordable and Non-Recordable steps.

Navigation: Insert menu->Step Generator Or Use Shortcut key F7 The Step Generator enables us to add steps by selecting from a range of contextsensitive options and entering the required values. In the Step Generator dialog box we can define steps that use: Test object operations (tests only) Utility object operations Calls to library functions (tests only), VBScript functions, and internal script functions For example, we can add a step that checks that an object exists, or that stores the returned value of a method as an output value or as part of a conditional statement. We can parameterize any of the values in our step. Note: we can use the Step Generator to insert steps in tests and function libraries. Hover, in function libraries, we cannot use the Step Generator to access test object names or collections, or to access the list of library functions. Before we open the Step Generator to define a new step, we first select where in our test the new step should be inserted. After we open the Step Generator, we first select the category for the step operation (test object, Utility object or function) and the required object or the function library. We can then select the appropriate operation (method, property, or function) and define the arguments and return values, parameterizing them if required. The Step Generator then inserts a step with the correct syntax into y test. We can continue to add further steps at the same location without closing the Step Generator. We can open the Step Generator from the Keyword View, Expert View, or Active Screen. Adding Comments to Scripts Comments are statements that are ignored by the script host when the script runs. To ensure that the script host does not attempt to interpret a comment as a command,

we must preface each comment with a comment delimiter. VBScript allows two delimiters: the single quotation mark (') and the REM statement. For example, both of the following lines of code are valid comments: ' This is a comment using a single quote delimiter. REM This is a comment using the REM statement as a delimiter.

Although most script writers use the single quotation mark, you might consider following the single quotation mark with an asterisk when commenting your code: '* This is another comment. This approach has two advantages over the single quotation mark alone. First, it makes the comment stand out from the rest of the text; a single quotation mark by itself can be difficult to see at times. Second, the single quotation mark is a valid VBScript character that has uses beyond delimiting comments. This can be a problem if we use an automated procedure to extract comments from a script; such a procedure might also retrieve items that are not comments. Because we are less likely to use '* anywhere else in our script, it makes a good delimiter. Always include comments on separate lines except for comments that accompany the declaration of a variable. Comments included on the same line as a VBScript statement (end-of-the-line comments) are valid but can be difficult to read. For example, compare the two commenting styles in the following script snippet; in the

first half of the script, comments are placed on the same line as a VBScript statement, while in the second half of the script, the comments are placed on separate lines. Most people find it easier to quickly identify the comments used in the second half of the script. ----------------------------------------------On Error Resume Next Set WshNetwork = WScript.CreateObject("WScript.Network") WshNetwork.MapNetworkDrive "Z:", "\\RemoteServer\Public" '* Map drive Z. If Err.Number <> 0 Then '* Check to make sure the operation succeeded. Err.Clear Wscript.Echo "The drive could not be mapped." End If '* Map drive Z. WshNetwork.MapNetworkDrive "Z:", "\\RemoteServer\Public" '* Check to make sure the operation succeeded. If Err.Number <> 0 Then Err.Clear Wscript.Echo "The drive could not be mapped." End If -----------------------------------------------

Code Commenting Conventions All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation. Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, especially through reference arguments, should also be described at the beginning of each procedure. Procedure header comments should include the following section headings. Section Heading: Comment Contents: Purpose: Assumptions: Remember the following points: Every important variable declaration should include an inline comment describing the use of the variable being declared. Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details.

At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful. Debugging Tests Debugging is a process of executing the script or a program in a User designed fashion with some temporary break points in order to identify the errors. For debugging, QTP is providing debug commands and breakpoints. Debug Commands: 1) Step Into (short cut key F11): a. It starts execution b. It executes one statement at a time. c. If it is function call, it opens the function, after that it executes one statement at a time. 2) Step Over (Short cut key F10):

a) It executes one statement at a time after execution starts b) It executes all functions statements at a time Note: After opening the function, if we use step over it executes one statement at a time only. 3) Step Out (shift +F11): It executes all remaining statements in a function at a time. Ex: Dim a,b,c a=100 b=200

c=a+b msgbox c msgbox "hello" Call hyderabad msgbox "bye bye" Note: Create a script and work on it Break Point: This feature is used for breaking the execution temporarily. Navigation: Place cursor in desired location >Debug menu>Insert/Remove break point Or Use short cut key (F9) Or Place mouse pointer before the statement and click. Note: If we want to execute Some part of the Test Script at a time and some other part of the test script step by step, there we can use breakpoints.

Debug viewer Pane: It is used for viewing, modifying or setting the value of the variables during the execution break with the help of 3 Tabs. 1. Watch 2. Variables 3. Command

Note: Through Debug Viewer Pane, We can watch variables whether the variables are taking correct values or not at a specific point of time. We can change Values of Variables temporarily. Ex : Dim x,y,z x=10 y=20 z=x+y msgbox z msgbox "Hello" x=35 y=67 z=x*y msgbox z msgbox "bye bye" Navigation: View menu > Debug Viewer > Use step into feature. Analyzing Test Results & Reporting Analyzing the Test Result is not a responsibility of QTP. After Running Tests, User (Test Engineer) has to analyze the test result. and send defect reports. QTP Result Window: After Running/Executing a test, then QTP Provide result window. we export test result from result window in Document (.Doc), HTML, XML and PDF formats. Note: QTP doen't provide batch wise test result, if we execute test batches. It provides test wise result only. Status of the Result: QTP has 4 types of result status a) Pass b) Fail c) Done d) Warning

Defining our own Result: Generally QTP provides, test results, if we use qtp tool features like checkpoints. suppose if we use flow control statements (conditional and Loop statements), then we have to define our own result. For defining our own results, QTP is providing an utility object called "Reporter" by using reporter, we can define our own results. Syntax: Reporter.ReportEvent status of the Result,"Result Step","message" Example" Reporter.ReportEvent micPass,"Res","Login operation Successful" exaplanation: Reporter- Utility object ReportEvent-Method micPass-Status of the Result. Res-Result step "Login operation Successful"- Message Status of the Result: 1) Pass -micPass or 0 2) Fail -micPass or 1 3) Done- micDone or 2 4) Warning- micDone or 3 Reporting Defects QTP is an Object based Test tool. We can create and execute tests using QTP. QTP Provides, various methods for crating and enhancing Tests. After Running Tests, QTP provides result in Result window and also provides a facility to define our own Results. Result Exporting facility also available in QTP Result window.

Any how Analyzing Results is the Responsibility of Test Engineer after running tests. After analyzing results, we can report defects in various methods. If we are using QTP for Functional Test Automation and Defect management manual, then entering defect details in company prescribed format and sending. If we are using Bugzilla or Zera or PR-Tracker like Bug Tracking tool, then after analyzing results, if we find any mismatches sending defects through the Bug tracking tool (Every Bug Tracking tool has its own defect report template) If we are using Quality center for Test management, then we can send defects directly from QTP result window. In between QTP and Quality Center back to back integration is available. Actions Action: Set of Statements for perfoming a Task(s) We divide our test into actions to streamline the process of testing.

Purpose of Actions: For understandability For reusing components Types of Actions: 1) Non Re usable actions 2) Re usable actions 3) External actions Operations on Actions: • Creating Actions • Splitting Actions • Renaming Actions

• Deleting Actions • Calling an Action • Copying an Action • Making an Action Reusable/Non Reusable Creating an Action: Insert>call to new action>enter name of the action>click ok Steps: 1. Create required actions(ex login, insert,delte) 2. Prepare Scripts for those actions. Splitting an action: Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name & action 2 name. Steps: 1. Generate total test in the default action 2. Split into meaningful actions. Note: At a time we can split one actions into 2 actions. Renaming actions: Select desired action in action drop down box> edit menu>action>rename action>modify the name>click ok. Deleting Actions: Select desired action in action drop down box>edit menu>action>delete action>confirm deletion. Calling an action: Insert>call to existing action>browse path of the test>select desired action>click ok. Note: U can’t edit

Copying an action: Insert>call to copy of action>browse path of the test>select desired action>click ok. Note: we can edit this action. Making an action reusable: Select Non Reusable action >edit >action>action properties>check reusable action check box >click ok. VB Script String Functions String Functions 1) Left Function Returns a specified number of charectors of a given string from left side Syntax: variable=Left(string,Lengh) Example: Dim val,x val="Hyderabad" x=Left(val,3) msgbox x ' Output: Hyd

val="9247837478" x=Left(val,1) msgbox x ' Output: 9

val="H92yderabad" x=Left(val,3) msgbox x ' Output: H92

x=Left(9247837478,5) msgbox x ' Output: 92478 val=#10-10-10#

x=Left(val,3) msgbox x ' Output: 10/ 2) Right Function Returns a specified number of charectors of a given string from Right side Example: Dim val,x val="Hyderabad" x=Right(val,3) msgbox x ' Output: bad

val="9247837478" x=Right(val,1) msgbox x ' Output: 8

val="H92yderabad" x=Right(val,3) msgbox x ' Output: bad

x=Right(9247837478,5) msgbox x ' Output: 37478 val=#10-10-10# x=Right(val,5) msgbox x ' Output: /2010 3) Mid function Returns a specified number of charectors of a given string Example: Dim val,x val="Hyderabad"

x=Mid(Val,5,3) msgbox x ' Output: rab val="Hyderabad" x=Mid(Val,5) msgbox x ' Output: rabad val="9247837478" x=Mid(val,6,5) msgbox x ' Output: 37478

val="H92yderabad" x=Mid(val,1) msgbox x ' Output: H92yderabad

x=Mid(9247837478,5) msgbox x ' Output: 837478 val=#10-10-10# x=Mid(val,5) msgbox x ' Output: 0/2010 4) StrReverse retuns reverse value of a string Example: Dim val,x val="Hyderabad" x=StrReverse(val) msgbox x 'Output dabaredyH val="001" x=StrReverse(val) msgbox x 'Output: 100 val=1002

x=StrReverse(val) msgbox x 'Output: 2001 val=#10-10-10# x=StrReverse(val) msgbox x 'Output: 0102/01/01 x=StrReverse("Hyderabad") msgbox x 'Output: dabaredyH x=StrReverse(100) msgbox x 'Output: 001 5) StrComp Function It compares two string (Binary and textual) if a) Both are equal, returns 0(zero) b) String 1 greater than string 2, returns 1(one) b) String 2 greater than string 1, returns -1 Example: Dim str1,str2,x str1="India" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="india" str2="INDIA" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="India" str2="Indian"

x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="Ndia" x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 1 str1=100 str2=100 x=StrComp(str1,str2,1) msgbox x 'Output 0 str1=100 str2=101 x=StrComp(str1,str2,1) msgbox x 'Output -1 6) Lcase function Coverts Upper case values into Lower case Dim val,x val="HYDERABAD" x=Lcase(val) msgbox x 'Output hyderabad val="Hyderabad" x=Lcase(val) msgbox x 'Output hyderabad val="HederabaD" x=Lcase(val) msgbox x 'Output hyderabad

val="hyderabad" x=Lcase(val) msgbox x 'Output hyderabad x=Lcase("HYDERABAD") msgbox x 'Output hyderabad

7) Ucase function Coverts Lower case values into Upper case Example: Dim val,x val="HYDERABAD" x=Ucase(val) msgbox x 'Output HYDERABAD val="Hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD val="HederabaD" x=Ucase(val) msgbox x 'Output HYDERABAD val="hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD x=Ucase("HYDERABAD") msgbox x 'Output HYDERABAD 8) LBound, UBound Functions

Example:

Dim x(3), y(4,5)

Msgbox Lbound(x) '0

Msgbox UBound(x)'3

'Find size of the Array

Msgbox UBound(x)+1

Msgbox Lbound(y,1) '0

Msgbox Lbound(y,2) '0

Msgbox UBound(y,1) '4

Msgbox UBound(y,2) '5 Environment Variables in QTP These are global variables; if you want to use some variables globally (From number of tests) declaring as global variables is better. If we declare as local variables in number of tests, modifications are difficult. Types of Environment variables: 1. Built in variables: These are system defined variables, we can access from all tests but these are designed as read only. 2. User defined variables: Variables that we predefine in the active external environment variables file. We can create as many files as we want and we can change values of variables.

Usage of environment variables: Syntax: Variable = Environment(“environment variable name”) Ex: X=Environment (“ActionName”) Msgbox x Example Script: ProductDir =environment ("ProductDir") app= "\samples\flight\app\flight4a.exe" Systemutil.Run ProductDir & app Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "kajal" Dialog("Login").WinEdit("Password:").SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407" Dialog("Login").WinButton("OK").Click Creating user defined environment variables: Navigation: File > settings > Environment > select variable type as user defined > click add icon (+) > enter variable name & Value > click ok (like this we can create number of variables) > click export > browse path & enter file name, save with xml extension > click ok. Associating environment variable file: Navigation: File > settings >Environment > select variable type as user defined > check “load variables and values from the external file” > browse path of the xml file > click apply & ok. Or We can load environment file directly

Environment.loadfromfile”path of the xml file” Usage of user defined Environment variables: Associate environment file to current test: Variable = Environment (“Variable Name”) X=environment (“city”) Msgbox x Modifying Environment files: Select XML file>open with notepad>modify the values>Save. Regular Expressions in QTP What is Regular Expression? It is a way of representing data using symbols. They are often used within matching, searching or replacing algorithms. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values. Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in Descriptive programming. We can define a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified.

We can define the text string as a regular expression, when creating a text checkpoint to check that a varying text string is displayed on our application, For XML checkpoints we can set attribute or element values as regular expressions. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character. Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character. b) Matching Any Single Character: A period (.) instructs QTP to search for any single character (except for \n). Ex: welcome. Matches welcomes, welcomed, or welcome followed by a space or any other single character. c) Matching Any Single Character in a List: Square brackets instruct QTP to search for any single character within a list of characters. Ex: To search for the date 1867, 1868, or 1869, enter: 186[789] d) Matching Any Single Character Not in a List: When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in the list except for the ones specified in the string. Example: [^ab] Matches any character except a or b. e) Matching Any Single Character within a Range:

To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character. Example: For matching any year in the 2010s, enter: 201[0-9] f) Matching Zero or More Specific Characters: An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character. For example: ca*r Matches car, caaaaaar, and cr g) Matching One or More Specific Characters: A plus sign (+) instructs QTP to match one or more occurrences of the preceding character. For example: ca+r Matches car and caaaaaar, but not cr. h) Matching Zero or One Specific Character: A question mark (?) instructs QTP to match zero or one occurrences of the preceding character. For example: ca?r Matches car and cr, but nothing else. i) Grouping Regular Expressions: Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * , + , ? , { } ).

j) Matching One of Several Regular Expressions: A vertical line (|) instructs QTP to match one of a choice of expressions. k) Matching the Beginning of a Line: A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character. l) Matching the End of a Line: A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character. m) Matching Any AlphaNumeric Character Including the Underscore: \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 09, _). n) Matching Any Non-AlphaNumeric Character: \W instructs QTP to match any character other than alphanumeric characters and underscores. o) Combining Regular Expression Operators: We can combine regular expression operators in a single expression to achieve the exact search criteria we need. For example, start.* Matches start, started, starting, starter, and so forth. we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric characters. For example: [a-zA-Z]* To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4 digits between 1000-1200. The regular expression below matches any number between 0 and 1200. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200) RegExp object

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method b) Replace Method c) Test Method Regular Expressions Examples: 1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") strCurrentDirectory = objShell.CurrentDirectory Set objFolder = objFS.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Files Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) For Each objFile In colFiles bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End If

Next 2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.txt" Set objFS = CreateObject("Scripting.FileSystemObject") Set objTS = objFS.OpenTextFile(strFileName) strFileContents = objTS.ReadAll WScript.Echo "Searching Within: " WScript.Echo strFileContents objTS.Close Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) Set colMatches = objRE.Execute(strFileContents) WScript.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value Virtual Object Configuration

Virtual Object Configuration:

Virtual Object Configuration is a process of making the QTP to treat a specified area or a user defined object as Virtual Object.

Virtual objects enable us to create and run tests on objects that are not normally recognized by QTP.

We can manage the virtual objects defined on our computer using the Virtual Object Manager.

Navigation:

Select Tools Menu Go to Virtual objects Select ‘New Virtual Object’ option Click Next Mark the area in the Application with help of mark object button Click next Select one of the following options o o Entire Parent hierarchy Parent only Click on Next Specify the Desired object name Specify the Desired collection name Click finish

Virtual Object Manager:

Virtual object Manager feature enable us to create and manage Virtual Objects Batch Testing or Batch Execution

Executing a group of Tests or series of tests at a time is known as Batch Testing or Batch

Execution. For performing Batch Testing, QTP is providing a separate Tool called Test Batch Runner. Steps for Batch Testing:

1). Create Individual Tests and Run once. 2). Open 'Test batch Runner' Tool and Form Batches. 3) Provide permission to 'Test batch Runner' to run tests 4). Run or Execute Test Batches from Test Batch Runner. 5) View Test wise Result in 'Test Result Viewer'. Note: QTP doesn’t provide Batch wise result. Forming a Test Batch: Launch Test Batch Runner. Navigation: Start>program>quicktest professional>Tools>Test Batch Runner>File>new>batch>add>browse path of the test (like this add number of tests)>save with MTB extension (Module test batche)>close test batch runner. Running or Executing a Test Batch Open Test Batch Runner Tool Navigation: File>open>browse path of the test batch>batch>run Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one. Note: Allowing other products to Run Tests.

Navigation: Tools>Options>Run>check allow other mercury products>apply & Ok Executing partial Test Batch Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch. Recovery Scenarios Recovery Scenario Manager To recover from unexpected events and errors that are occurred in the test environment during run session, we can use Recovery Scenario Manager. For good recovery, error must be known the occurrence is unknown. There are (4) Types of events such as: (i) Application Crash An open application fails during Test Run. Navigation: Resources Menu -> Recovery Scenario Manager-> Click New-> Click Next -> Select Application Crash as Trigger event->Next ->Select selected executable application->Next ->Select Recovery Operation [Keyboard, Mouse Operation, Close Application Process, function Call, Restart, Microsoft Windows] ->Next ->If you want to check Add another operation else uncheck->Next ->Next ->Enter Scenario Name ->Next->Select Option ->Finish ->Close ->Save the scenario in specified location with “.qrs” (qrs stands for QuickTest Recovery Scenario.) (ii) Popup Window. To handle unwanted popups. Navigation: Resources Menu ->Recovery Scenario Manager ->New ->Next ->Select “Popup Window” as Trigger event ->Next ->Click on Hand Icon ->Show unwanted

window with Hand icon ->Next ->Next ->Select function call as Recovery Operation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browse the .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] ->Next ->Enter Scenario Name ->Next ->Select Option -> Finish ->Save the scenario with “.qrs” ->Record required Recovery Operation [Click ok, Click Cancel] take the script into function ->Save the library file ->Click Run (iii) Test Run Error. A step in your test does not run successfully then Test Run Error can be raised. Navigation : Resources Menu ->Recovery Scenario Manager ->New ->Next ->Select “Testrunerror Window” as Trigger event ->Next ->select any error o ->Next ->Next ->Select function call as Recovery Operation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browse the .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] ��Next ��Enter Scenario Name ��Next ��Select Option �� Finish ��Save the scenario with “.qrs” ��Record required Recovery Operation [Click ok, Click Cancel] take the script into function ��Save the library file ��Click Run (iv) Object State. The property values of an object in your application match specified values. You can specify property values for each object in the hierarchy. Navigation: Resources Menu -> Recovery Scenario Manager -> New -> Next -> Select “Object state

Window” as Trigger event -> Next -> Click on Hand Icon -> Show object with hand icon -> Next -> Next->select object property with value (enabled ,false)->click next -> Select function call as Recovery Operation -> Next [Open Notepad -> Save empty file with .vbs extension] -> Browse the .vbs fie path -> Next -> Uncheck Add another Recovery Operation -> Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] -> Next-> Enter Scenario Name -> Next -> Select Option -> Finish -> Save the scenario with “.qrs” -> Record required Recovery Operation [Click ok, Click Cancel] take the script into function -> Save the library file -> Click Run File System Operations

File System:

Its an operating system feature, it allows users to create, modify, view and delete; drives,folders and files

VB Script is providing an object called scripting.filesystemobject and some methods for performing file systems operations

File System Object Model:

The File System Object (FSO) model provides an object-based tool for working with folders and files. It allows us to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files. We can also employ the traditional Visual Basic statements and commands.

The FSO model gives our application the ability to create, alter, move, and delete folders, or to determine if and where particular folders exist. It also enables us to get information about folders, such as their names and the date they were created or last modified.

The FSO model makes processing files much easier as well. When processing files, our primary goal is to store data in an efficient, easy-to-access format. We need to be able to create files, insert and change the data, and output (read) the data. Although we can store data in a database, doing so adds a significant amount of overhead to our application. We may not want to have such overhead, or our data access requirements may not call for the extra functionality associated with a full-featured database. In this case, storing our data in a text file or binary file is the most efficient solution.

The FSO model, contained in the Scripting type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object; however, the FSO model does not support binary files. To manipulate binary files, use the FileOpen Function with the Binary keyword.

Examples:

1) Create a folder Dim fso, strFolder strFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok" Set fso=createobject("scripting.filesystemobject") fso.CreateFolder(strFolder)

2) Create a folder Dim fso, strFolder strFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok" Set fso=createobject("scripting.filesystemobject") If fso.FolderExists(strFolder) Then msgbox "Folder already exists" else fso.CreateFolder(strFolder) End If

3) Data Driven Testing by fetching Test data directly from a Text file. '********************************************************* 'Test Requirement: Data Driven Testing by Fetching Test data directly from a Text file. 'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requisites: 'vinod.txt (Test Data) 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Read the Data & Split the Data 'Generating the Login Operation 'Pass Parameters '********************************************************

Dim objFso, myFile, myLine, myField Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-Append myFile.SkipLine Do Until myFile.AtEndOfStream myLine=myFile.ReadLine myField=Split(myLine,",") SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0) Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1) wait 2 Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Loop myFile.Close Set objFso=Nothing Database connections Database connection is a facility in computer science that allows client software to communicate with database server software, whether on the same machine or not. SQL Server connection strings SQL ODBC connection strings Standard Security: "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Uid=Y our_Username;Pwd=Your_Password;" Trusted connection:

"Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Truste d_Connection=yes;" SQL OLE DB connection strings Standard Security: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" Trusted connection: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;" SQL OleDbConnection .NET strings Standard Security: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" Trusted connection: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;" SQL SqlConnection .NET strings Standard Security: 1. "Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" < br>2. "Server=Your_Server_Name;Database=Your_Database_Name;UserID=Your_Username;P assword=Your_Password;Trusted_Connection=False" Trusted connection: 1. "Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;" 2."Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=Tr ue;" MS Access connection strings MS Access ODBC connection strings Standard Security: "Driver= {MicrosoftAccessDriver(*.mdb)};DBQ=C:\App1\Your_Database_Name.mdb;Uid=Your_U sername;Pwd=Your_Password;"

Workgroup: "Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\App1\Your_Database_Name.mdb; SystemDB=C:\App1\Your_Database_Name.mdw;" Exclusive "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\App1\Your_Database_Name.mdb; Exclusive=1; Uid=Your_Username; Pwd=Your_Password;" MS Access OLE DB & OleDbConnection (.NET framework) connection strings Open connection to Access database: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; User Id=admin; Password=" Open connection to Access database using Workgroup (System database): "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:System Database=c:\App1\Your_System_Database_Name.mdw" Open connection to password protected Access database: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:Database Password=Your_Password" Open connection to Access database located on a network share: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\Server_Name\Share_Name\Share_Path\Your_Database_Name.mdb" Open connection to Access database located on a remote server: "Provider=MS Remote; Remote Server=http://Your-Remote-Server-IP; Remote Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb" MySQL connection strings MySQL ODBC connection strings Open connection to local MySQL database using MySQL ODBC 3.51 Driver "Provider=MSDASQL; DRIVER={MySQL ODBC 3.51Driver}; SERVER= localhost; DATABASE=Your_MySQL_Database; UID= Your_Username; PASSWORD=Your_Password; OPTION=3" MySQL OLE DB & OleDbConnection (.NET framework) connection strings Open connection to MySQL database: "Provider=MySQLProv;Data Source=Your_MySQL_Database;User Id=Your_Username;

Password=Your_Password;" Oracle connection strings Oracle ODBC connection strings Open connection to Oracle database using ODBC "Driver= {Microsoft ODBCforOracle};Server=Your_Oracle_Server.world;Uid=Your_Username;Pwd=Your_Pas sword;" Oracle OLE DB & OleDbConnection (.NET framework) connection strings Open connection to Oracle database with standard security: 1. "Provider=MSDAORA;Data Source= Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;" 2. "Provider= OraOLEDB.Oracle;Your_Oracle_Database;UserId=Your_Username;Password=Your_Pass word;" Open trusted connection to Oracle database "Provider= OraOLEDB.Oracle;DataSource=Your_Oracle_Database;OSAuthent=1;" AOM Scripting (Automation Object Model) Object Model: An object model is a structural representation of software objects (classes) that comprise the implementation of a system or application. An object model defines a set of classes and interfaces, together with their properties, methods and events, and their relationships. We can use QTP Automation object Model to write scripts, that automate our QTP operations. QTP Automation object model provides objects, methods and properties that enable us to control QTP from another application.

We can use Scripting languages or programming languages such as VBscript, Java script or VC++, .Net for automating QTP operations.

Example: option explicit Dim qtApp,qtTest Set qtApp=createobject ("Quicktest.Application") qtApp.Launch qtApp.visible=True qtApp.open "C:\Documents and Settings\admin\My Documents\login" Set qtTest=qtApp.Test qtTest.run qtTest.close qtApp.open "C:\Documents and Settings\admin\My Documents\open order" Set qtTest=qtApp.Test qtTest.run qtTest.close qtApp.quit Note: AOM Script can be used in Automation framework as an Initialization script. Dynamic handling of object Repositories Loading repositories during running, finding path of the repositories and removing repositories is called Dynamic Handling of Object Repositories. Using this feature we can increase QTP performance. To do this, QTP is providing an object called “RepositoriesCollection”. Syntax for Loading a Repository: RepositoriesCollection.Add “Path of the Repository File” Syntax for finding Position of the Repository: Variable=RepositoriesCollection.Find(“Path of the Repository”) Syntax for Removing the Repository:

RepositoriesCollection.Remove(position) Syntax for Removing All Repositories: RepositoriesCollection.RemoveAll Example: RepPath="C:\Documents and Settings\Administrator\My Documents\Login.tsr" RepositoriesCollection.Add (RepPath) systemutil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "sudhakar" Dialog("Login").WinEdit("Password:").Set "mercury" Dialog("Login").WinButton("OK").Click pos=RepositoriesCollection.Find(RepPath) RepositoriesCollection.Remove(pos) RepositoriesCollection.RemoveAll VB Script for QTP Scripting Vs Programming Scripting Language: Scripting Language is a Light weight language, no need to compile them separately, during execution they automatically compile an run. 1) It is an Interpreter based Language 2) Interpreter converts high level instructions into machine language line by line 3) It doesn’t create executable file. 4) No need to compile the program 5) It takes less code for achieving tasks. 6) It greatly reduces development time 7) It reduces maintenance of cost 8) Implicit Support of Data Types. 9) Limited support for User Interface Design 10) Limited or No Support for Graphics Design Example Scripting Languages are: Shell, Perl, VB Script, Java Script, Python, Ruby, Rexx, PHP Etc..

Programming Language: 1) It is a compiler based Language. 2) Compiler converts the whole program in single short into machine language. 3) It Creates .exe file. Need to compile the program 4) It takes numerous lines of code 5) It increases development time 7) It Increases maintenance of cost 8) Explicit support of Data Types 9) Rich support for User Interface Design 10) Rich Support for Graphics Design Example Programming Languages are: COBOL, Basic, C, C++, VC++, VB Etc... VB Script Fundamentals And Features VB Script has several purposes: a) Client side scripting in the Web (HTML)(Browser) (IE) b) Server side scripting in the Web (ASP) (Web Server)(IIS) c) Network Administration (Server OS) (WSH-Windows Script Host) d) System Administration (Client OS) (WSH-Windows Script Host) e) Test Automation (QTP) (QTP) Our QTP Point of view below are the learning objectives: a) Adding Comments b) Data types c) Declarations (Variables (Scalar and Array),Constants)) d) VB Script Operators i) Arithmetic Operators (Including Concatination operators)

ii) Comparison iii) Logical e) Flow Control Statements (a. Conditional Statements) i) If...Then...Else...End If ii) Select Case...Case...Case Else...End Select

f) Flow Control Statements (b. Loop Statements) i) For...Next ii) While...Wend iii) Do While/Until...Loop iV) For Each...Next g) VB Script Procedures(Functions) i) Built-in Functions(String, Array, Math,Date & Time, Conversion functions etc...) ii) User defined 1) Sub Procedures 2) Function Procedures h) Coding Convensions -------------------i) File System Operations j) Excel sheet Operations k) database Operations l) Other VB Script Objects i) Dictionary Object ii) Word iii) Internet Explorer Object iV) RegExp Object m) Regular expressions k) Error Handling VB Script Comments

Comments The comment argument is the text of any comment we want to include. Purpose of comments: o We can use comments for making the script understandable. o We can use comments for making one or more statements disable from execution. Syntax Rem comment (After the Rem keyword, a space is required before comment.) Or Apostrophe (') symbol before the comment Comment/Uncomment a block of statements o Select block of statement and use short cut key Ctrl + M (for comment) o Select comment block and use short cut key Ctrl + Shift + M (for uncomment) VB Script Variables Definition 1): Variable is a named memory location for storing program information Definition 2): A variable is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running. Purpose of Variable: a) Comparing values Example: Dim x,y,a x=100 y=100 a=x=y Msgbox a 'It returns True

b) Holding Program Result Example: Cost=Tickets*Price c) Passing parameters d) To store data that returned by functions Example: myDate=Now ‘ It returns current data & time e) To hold data Example: myName=”gcreddy” Declaring Variables We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. For Example: Dim x, y, city, gcreddy We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in our script. Option Explicit Statement Forces explicit declaration of all variables in a script. Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable.

MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. A variable name: a) Must begin with an alphabetic character. Dim abc 'Right Dim 9ab 'Wrong Dim ab9 'Right b) Cannot contain an embedded period. Dim abc 'Right

Dim ab.c 'worng Dim ab-c 'wrong Dim ab c 'wrong Dim ab_c 'Right c) Must not exceed 255 characters. d) Must be unique in the scope in which it is declared. Scope of Variables A variable's scope is determined by where we declare it. When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable. If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope. Example:

Dim x,y,z x=10 y=20 z=x+y msgbox z 'Returns 30 Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90 End Function Call res Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: A = 200 City = “Hyderabad” X=100: Y=200

Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) Although the number shown in the parentheses is 3, all arrays in VBScript are zerobased, so this array actually contains 4 elements. We assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 4, data can be assigned to the elements of an array as follows: A(0) = 256 A(1) = 324 A(2) = 100 A(3) = 55 Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5, 10) In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.

Dynamic Arrays We can also declare an array whose size changes during the time our script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example: Dim MyArray() ReDim AnotherArray() To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place. ReDim MyArray(25) ReDim Preserve MyArray(30) There is no limit to the number of times we can resize a dynamic array, although if we make an array smaller, we lose the data in the elimina VB Script Data Types VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.

Variant Subtypes Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, we can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floatingpoint numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, we can just put the kind of data we want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains. The following table shows subtypes of data that a Variant can contain. VB Script Operators Operators are used for performing mathematical, comparison and logical operations. VB Script has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators. Operator Precedence When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained. When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the leftto-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence. 1) Arithmetic Operators:

Operator Description 1) Exponentiation Operator (^) Raises a number to the power of an exponent 2) Multiplication Operator (*) Multiplies two numbers. 3) Division Operator (/) Divides two numbers and returns a floating-point result. 4) Integer Division Operator (\) Divides two numbers and returns an integer result. 5) Mod Operator Divides two numbers and returns only the remainder. 6) Addition Operator (+) Sums two numbers. 7) Subtraction Operator (-) Finds the difference between two numbers or indicates the negative value of a numeric expression. 8) Concatenation Operator (&) Forces string concatenation of two expressions. Example: Dim a,b,c a=10 b=3 c=a^b msgbox c '1000 c=a*b msgbox c '30 c=a/b msgbox c '3.33333333 c=a\b msgbox c '3 c=a mod b msgbox c '1 c=a-b

msgbox c '7 Dim a,b,c a=10 b=2 c=3 d=c*a^b 'c=a+b msgbox d '1000 Addition (+) operator Dim a,b,c a=10 b=2 c=a+b msgbox c '12 (if both are numeric, then it adds) a="10" b=2 c=a+b msgbox c '12 (one is string another numeric, then it adds) a="10" b="2" c=a+b msgbox c '102 (if both are strings, then it concatenates) a="hydera" b="bad" c=a+b msgbox c 'hyderabad a="gagan" b=2 c=a+b msgbox c 'error Concatenation Operator

Dim a,b,c a=10 b=2 c=a&b msgbox c '102 a="10" b=2 c=a&b msgbox c '102 a="10" b="2" c=a&b msgbox c '102 a="hydera" b="bad" c=a&b msgbox c '102 2) Comparison Operators Used to compare expressions. Operator Description 1) = (Equal to) Used to compare expressions. 2) <> (Not equal to) Used to compare expressions. 3) < Less than 4) > Grater than 5) <= Less than or equal to 6) >= Greater than or equal to 7) Is Object equivalence

3) Concatenation Operators Operator Description 1) Addition Operator (+) Sums two numbers

If Then 1) Both expressions are numeric Add. 2) Both expressions are strings Concatenate. 3) One expression is numeric and the other is a string Add. 2) Concatenation Operator (&) Forces string concatenation of two expressions.

4) Logical Operators Operator Description Syntax 1) Not Performs logical negation on an expression result= Not expression 2) And Performs a logical conjunction on two expressions. result= expression1 And expression2 3) Or Performs a logical disjunction on two expressions. result= expression1 Or expression2 4) Xor Performs a logical exclusion on two expressions. result= expression1 Xor expression2 5) Eqv Performs a logical equivalence on two expressions. result= expression1 Eqv expression2 6) Imp Performs a logical implication on two expressions. result= expression1 Imp expression2 Methods Input and Out Put Operations InputBox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Example: Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) MsgBox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

Example: Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") MyVar contains either 1 or 2, depending on which button is clicked. VB Script Constants A constant is a meaningful name that takes the place of a number or string and never changes. Creating Constants We create user-defined constants in VBScript using the Const statement. Using the Const statement, we can create string or numeric constants with meaningful names and assign them literal values.

Const statement

Declares constants for use in place of literal values.

Example:

Const MyString = "This is my string." Const MyAge = 49 Const CutoffDate = #6-1-97#

Note that String literal is enclosed in quotation marks (" ").

Represent Date literals and time literals by enclosing them in number signs (#). We declare multiple constants by separating each constant name and value with a comma. For example: Const price= 100, city= “Hyderabad”, x= 27 Flow Control (Conditional Statements) We can control the flow of our script with conditional statements and looping statements. Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript: 1) If…Then…Else Statement 2) Select Case Statement Making Decisions Using If...Then...Else The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. If...Then...Else statements can be nested to as many levels as you need. 1) Running a Statement if a Condition is True (single statement) To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 2) Running Statements if a Condition is True (multiple statements) To run more than one line of code, we must use the multiple-line (or block) syntax. This

syntax includes the End If statement. Dim x x= 20 If x>10 Then msgbox "x value is: "&x msgbox "Bye Bye" End If 3) Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False. Example: Dim x x= Inputbox (" Enter a value") If x>100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Big Number" Msgbox "X value is: "&X Else Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&X End If 4) Deciding Between Several Alternatives A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities. Example: Dim x x= Inputbox (" Enter a value")

If x>0 and x<=100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" Else Msgbox "Hello Sir" Msgbox "X is a Grand Number" End If End If End If 5) Executing a certain block of statements when two / more conditions are True (Nested If...) Example: Dim State, Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") If state= "AP" Then If Region= "Telangana" Then msgbox "Hello G.C.Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9"

End If End If End If End If Making Decisions with Select Case The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable. Example: Option explicit Dim x,y, Operation, Result x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") Operation= Inputbox ("Enter an Operation") Select Case Operation Case "add" Result= cdbl (x)+cdbl (y) Msgbox "Hello G.C.Reddy" Msgbox "Addition of x,y values is "&Result Case "sub" Result= x-y Msgbox "Hello G.C.Reddy" Msgbox "Substraction of x,y values is "&Result Case "mul" Result= x*y Msgbox "Hello G.C.Reddy" Msgbox "Multiplication of x,y values is "&Result

Case "div" Result= x/y Msgbox "Hello G.C.Reddy" Msgbox "Division of x,y values is "&Result Case "mod" Result= x mod y Msgbox "Hello G.C.Reddy" Msgbox "Mod of x,y values is "&Result Case "expo" Result= x^y Msgbox "Hello G.C.Reddy" Msgbox"Exponentation of x,y values is "&Result Case Else Msgbox "Hello G.C.Reddy" msgbox "Wrong Operation" End Select Flow Control (Loop Statements) o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False; o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times. The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array. 1) Using Do Loops We can use Do...Loop statements to run a block of statements an indefinite number of

times. The statements are repeated either while a condition is True or until a condition becomes True. a) Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True i) Do While condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" Loop ii) Do Statements --------------------Loop While condition

Example: Dim x x=1 Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5

b) Repeating a Statement Until a Condition Becomes True iii) Do Until condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP" Loop Or, we can use this below syntax: iv) Do Statements --------------------Loop Until condition Or, we can use this below syntax: Example: Dim x x=1 Do Msgbox “Hello G.C.Reddy” Msgbox "Hello QTP" x=x+1 Loop Until x=5 2 While...Wend Statement Executes a series of statements as long as a given condition is True. Syntax: While condition

Statements --------------------Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G.C.Reddy" msgbox "Hello QTP" Wend 3) For...Next Statement Repeats a group of statements a specified number of times. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.C.Reddy" Next 4) For Each...Next Statement Repeats a group of statements for each element in an array or collection. Syntax: For Each item In array Statements Next Example: (1

Dim a,b,x (3) a=20 b=30 x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next Example: (2 MyArray = Array("one","two","three","four","five") For Each element In MyArray msgbox element Next VB Script Procedures User Defined Functions In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure. 1) Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). Syntax:

Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1, argument2) Statements --------------------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2 2) Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements -----------

----------End Function Or Function Procedure name (argument1, argument2) Statements --------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function 3) Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas. 4) Using Sub and Function Procedures in Code A Function in our code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. 5) Examples: (here, I used Flight Reservation Application for creating Functions, why because, It is the default application for QTP, anybody can practice easily...G C Reddy) '******************************************* ' Login Operation '******************************************* Function Login(Agent,Pwd) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Pwd Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(10) Then Login="Login Operation Sucessful" 'Msgbox Login else Login="Login Operation Unsucessful" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click 'Msgbox Login End If

End Function '*************************************** ' Closing Application '*************************************** Function Close_App() if Window("Flight Reservation").Exist(3) Then Window("Flight Reservation").Close End If End Function '*************************************** ' Open Order '*************************************** Function Open_Order(ord) ordnum=0 On Error Resume Next Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty ("text") ordnum=cdbl (ordnum) If ord=ordnum Then Open_Order= "Order Number "&ordnum&" Opened Sucuessfully" 'Msgbox Open_Order else Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available" Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click 'Msgbox Open_Order End If End Function '****************************************** ' Update Order '******************************************

Function Update_Order(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click wait(10) update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text") If update="Update Done..." Then Update_Order= "Order Updated Sucussfully" 'Msgbox Update_Order Else Window("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").Click Update_Order= "Order Not Updated" 'Msgbox Update_Order End If End Function '****************************************** ' Function to send a mail '****************************************** Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit Set m = Nothing Set otl = Nothing End Function Call SendMail("gcreddy@gcreddy.com","hi","This is test mail for testing","") VB Script Errors Generally Errors in VB Script are 2 Types 1) VB Script Run-time Errors

VB Script run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated. Error Number Description: 429 ActiveX component can't create object 507 An exception occurred 449 Argument not optional 17 Can't perform requested operation 430 Class doesn't support Automation 506 Class not defined 11 Division by zero 48 Error in loading DLL 5020 Expected ')' in regular expression 5019 Expected ']' in regular expression 432 File name or class name not found during Automation operation 92 For loop not initialized 5008 Illegal assignment 51 Internal error 505 Invalid or unqualified reference 481 Invalid picture 5 Invalid procedure call or argument 5021 Invalid range in character set 94 Invalid use of Null 448 Named argument not found 447 Object doesn't support current locale setting 445 Object doesn't support this action 438 Object doesn't support this property or method 451 Object not a collection 504 Object not safe for creating 503 Object not safe for initializing 502 Object not safe for scripting 424 Object required 91 Object variable not set 7 Out of Memory 28 Out of stack space 14 Out of string space

6 Overflow 35 Sub or function not defined 9 Subscript out of range 5017 Syntax error in regular expression 462 The remote server machine does not exist or is unavailable 10 This array is fixed or temporarily locked 13 Type mismatch 5018 Unexpected quantifier 500 Variable is undefined 458 Variable uses an Automation type not supported in VBScript 450 Wrong number of arguments or invalid property assignment 2) VB Script Syntax Errors VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed. Error Number Description: 1052 Cannot have multiple default property/method in a Class 1044 Cannot use parentheses when calling a Sub 1053 Class initialize or terminate do not have arguments 1058 'Default' specification can only be on Property Get 1057 'Default' specification must also specify 'Public' 1005 Expected '(' 1006 Expected ')' 1011 Expected '=' 1021 Expected 'Case' 1047 Expected 'Class' 1025 Expected end of statement 1014 Expected 'End' 1023 Expected expression 1015 Expected 'Function' 1010 Expected identifier 1012 Expected 'If' 1046 Expected 'In' 1026 Expected integer constant 1049 Expected Let or Set or Get in property declaration

1045 Expected literal constant 1019 Expected 'Loop' 1020 Expected 'Next' 1050 Expected 'Property' 1022 Expected 'Select' 1024 Expected statement 1016 Expected 'Sub' 1017 Expected 'Then' 1013 Expected 'To' 1018 Expected 'Wend' 1027 Expected 'While' or 'Until' 1028 Expected 'While,' 'Until,' or end of statement 1029 Expected 'With' 1030 Identifier too long 1014 Invalid character 1039 Invalid 'exit' statement 1040 Invalid 'for' loop control variable 1013 Invalid number 1037 Invalid use of 'Me' keyword 1038 'loop' without 'do' 1048 Must be defined inside a Class 1042 Must be first statement on the line 1041 Name redefined 1051 Number of arguments must be consistent across properties specification 1001 Out of Memory 1054 Property Set or Let must have at least one argument 1002 Syntax error 1055 Unexpected 'Next' 1015 Unterminated string constant VB Script Functions Built-In Functions of VB Script o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3)

o Math (9) o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8) Important Functions

1) Abs Function Returns the absolute value of a number. Dim num num=abs(-50.33) msgbox num 2) Array Function Returns a variant containing an Array Dim A A=Array("hyderabad","chennai","mumbai") msgbox A(0) ReDim A(5) A(4)="nellore" msgbox A(4) 3) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Dim num num=Asc("A") msgbox num * It returns the value 65 * 4) Chr Function Returns the character associated with the specified ANSI character code.

Dim char Char=Chr(65) msgbox char * It returns A * 5) CInt Function Returns an expression that has been converted to a Variant of subtype Integer. Dim num num=123.45 myInt=CInt(num) msgbox MyInt 6) Date Function Returns the Current System Date. Dim mydate mydate=Date msgbox mydate 7) Day Function Ex1) Dim myday myday=Day("17,December,2009") msgbox myday Ex2) Dim myday mydate=date myday=Day(Mydate) msgbox myday 8) DateDiff Function Returns the number of intervals between two dates. Dim Date1, Date2, x Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("yyyy", Date1, Date2) Msgbox x 'Differnce in Years

Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("q", Date1, Date2) Msgbox x 'Differnce in Quarters Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("m", Date1, Date2) Msgbox x 'Differnce in Months Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("w", Date1, Date2) Msgbox x 'Differnce in weeks Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("d", Date1, Date2) Msgbox x 'Differnce in days Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("h", Date1, Date2) Msgbox x 'Differnce in Hours Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("n", Date1, Date2) Msgbox x 'Differnce in Minutes Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("s", Date1, Date2) Msgbox x 'Differnce in Seconds Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("y", Date1, Date2) Msgbox x 'Differnce in day of years

Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("a", Date1, Date2) Msgbox x 'Error Date1=#10-10-09# Date2=#10-10-11# x=DateDiff(Date1, Date2) Msgbox x 'Error 9) Hour Function Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Dim mytime, Myhour mytime=Now myhour=hour (mytime) msgbox myhour 10) Join Function Returns a string created by joining a number of substrings contained in an array. Dim mystring, myarray(3) myarray(0)="Chandra " myarray(1)="Mohan " myarray(2)="Reddy" mystring=Join(MyArray) msgbox mystring 11) Eval Function Evaluates an expression and returns the result. 12) Time Function Returns a Variant of subtype Date indicating the current system time. Dim mytime mytime=Time msgbox mytime

13) VarType Function Returns a value indicating the subtype of a variable. Dim x,y x=100 y=VarType(x) Msgbox y '2 (Integer) x="Hyderabad" y=VarType(x) Msgbox y '8 (String) x=#10-10-10# y=VarType(x) Msgbox y '7(Date format) x=100.56 y=VarType(x) Msgbox y ' 5(Double)

y=VarType(a) Msgbox y '0 (Empty) Set x =CreateObject("Scripting.FileSystemObject") y=VarType(x) Msgbox y '9(Automation Object) 14) Left Function Dim Val, x,y Val="Hyderabad" x=Left(Val,3) Msgbox x 'Hyd Val=100 x=Left(Val,1) Msgbox x '1

Val="Hyderabad" x=Left(Val,0) Msgbox x 'Null Val="Hyderabad" x=Left(Val,12) Msgbox x 'Hyderabad Val=#10-10-10# x=Left(Val,3) Msgbox x '10/ Val="Hyderabad" x=Left(Val) Msgbox x 'Error (Lengnth is Manditory) 14) Right Function Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". 15) Len Function Returns the number of characters in a string or the number of bytes required to store a variable. Ex 1): Dim Mystring mystring=Len("G.C.Reddy") msgbox mystring Ex 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring 16) Mid Function Returns a specified number of characters from a string.

Dim Val, x,y Val="Hyderabad" x=Mid(Val,3,4) Msgbox x 'dera Val=100 x=Mid(Val,1) Msgbox x '100 Val="Hyderabad" x=Mid(Val,6,7) Msgbox x 'abad Val="Hyderabad" x=Mid(Val,6,1) Msgbox x 'a Val="Hyderabad" x=Mid(Val,6,0) Msgbox x 'Null Val="Hyderabad" x=Mid(Val,12) Msgbox x 'Null Val=#10-10-10# x=Mid(Val,3,3) Msgbox x '/10 Val=#2010-10-10# x=Mid(Val,5) Msgbox x '/2010 Val="Hyderabad" x=Mid(Val) Msgbox x 'Error 17) Timer Function Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTime End Function Call myTime(2000) 17) isNumeric Function Dim MyVar, MyCheck MyVar = 53 MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "459.95" MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "45 Help" MyCheck = IsNumeric(MyVar) msgbox MyCheck * It Returns True/False like Result * 18) Inputbox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 19) Msgbox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Dim MyVar

MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") 20) CreateObject creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system Set objFso=createobject ("Scripting.FileSystemObject") 'creates and returns reference of the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (Ms-Excel files) Set objExcel = CreateObject("Excel.Application") 'creates and returns reference of the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents Set objWord = CreateObject("Word.Application") 'creates and returns reference of the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases Set objConnection = CreateObject("ADODB.Connection")

'creates and returns reference of the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records) Set objRecordSet = CreateObject("ADODB.Recordset") 'creates and returns reference of the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations Set objPPT = CreateObject("PowerPoint.Application") Set xmldoc = WScript.CreateObject("msxml2.domdocument") 21) Round Returns a number rounded to a specified number of decimal places.

Dim num num=172.499 num=Round(num) msgbox num 22) StrReverse It returns reverse value of the given sring x=strreverse ("dabaraedyh") msgbox x 23) strComp It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd) Dim x, y x="cd": y="bcd" comp=strcomp(x,y) msgbox comp 24) Replace It replace a sub string with given value (another sub string) mystring=Replace("kb script", "k","v") msgbox mystring Regular Expressions in QTP What is Regular Expression? It is a way of representing data using symbols. They are often used within matching, searching or replacing algorithms. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values. Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step

o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in Descriptive programming. We can define a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified. We can define the text string as a regular expression, when creating a text checkpoint to check that a varying text string is displayed on our application, For XML checkpoints we can set attribute or element values as regular expressions. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character. Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character. b) Matching Any Single Character: A period (.) instructs QTP to search for any single character (except for \n). Ex: welcome. Matches welcomes, welcomed, or welcome followed by a space or any other single character. c) Matching Any Single Character in a List: Square brackets instruct QTP to search for any single character within a list of characters. Ex: To search for the date 1867, 1868, or 1869, enter: 186[789]

d) Matching Any Single Character Not in a List: When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in the list except for the ones specified in the string. Example: [^ab] Matches any character except a or b. e) Matching Any Single Character within a Range: To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character. Example: For matching any year in the 2010s, enter: 201[0-9] f) Matching Zero or More Specific Characters: An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character. For example: ca*r Matches car, caaaaaar, and cr g) Matching One or More Specific Characters: A plus sign (+) instructs QTP to match one or more occurrences of the preceding character. For example: ca+r Matches car and caaaaaar, but not cr. h) Matching Zero or One Specific Character: A question mark (?) instructs QTP to match zero or one occurrences of the preceding character. For example:

ca?r Matches car and cr, but nothing else. i) Grouping Regular Expressions: Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * , + , ? , { } ). j) Matching One of Several Regular Expressions: A vertical line (|) instructs QTP to match one of a choice of expressions. k) Matching the Beginning of a Line: A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character. l) Matching the End of a Line: A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character. m) Matching Any AlphaNumeric Character Including the Underscore: \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 09, _). n) Matching Any Non-AlphaNumeric Character: \W instructs QTP to match any character other than alphanumeric characters and underscores. o) Combining Regular Expression Operators: We can combine regular expression operators in a single expression to achieve the exact search criteria we need. For example, start.* Matches start, started, starting, starter, and so forth. we can use a combination of brackets and an asterisk to limit the search to a

combination of non-numeric characters. For example: [a-zA-Z]* To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4 digits between 1000-1200. The regular expression below matches any number between 0 and 1200. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200) RegExp object VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method b) Replace Method c) Test Method Regular Expressions Examples: 1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") strCurrentDirectory = objShell.CurrentDirectory Set objFolder = objFS.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Files

Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) For Each objFile In colFiles bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.txt" Set objFS = CreateObject("Scripting.FileSystemObject") Set objTS = objFS.OpenTextFile(strFileName) strFileContents = objTS.ReadAll WScript.Echo "Searching Within: " WScript.Echo strFileContents objTS.Close Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) Set colMatches = objRE.Execute(strFileContents) WScript.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value VB Script Objects a) FileSystemObject

Scripting allows us to process drives, folders, and files using the FileSystemObject (FSO) object model.

Creating FileSystemObject:

Set Variable=CreateObject("Scripting.FileSystemObject") Example:

Dim objFso Set objFso=CreateObject("Scripting.FileSystemObject") objFso.CteateTextFile("D:\gcreddy.txt")

b) Dictionary

Creating Dictionary Object:

Set Variable=CreateObject("Scripting.Dictionary") Example:

c) Excel Application

Creating Excel Object:

Set Variable=CreateObject("Excel.Application") Example:

d) Word Application

Creating Word Object:

Set Variable=CreateObject("Word.Application") Example:

e) Shell

Creating Shell Object:

Set Variable= WScript.CreateObject("Wscript.Shell") Example:

f) Network

Creating Network Object:

Set Variable= WScript.CreateObject("WScript.Network") Example:

g) PowerPoint

Creating PowerPointObject:

Set Variable=CreateObject("PowerPoint.Application")

Example:

h) ADODB Connection

The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

Creating Database Connection Object:

Set Variable=CreateObject("ADODB.Connection") Example:

i) ADODB RecordSet

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields).

Creating Database RecordSet Object:

Set Variable=CreateObject("ADODB.RecordSet") Example:

j) ADODB Command

The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records.

Creating Database Command Object:

Set Variable=CreateObject("ADODB.Command") Example:

k) Error

Creating Error Object:

l) RegExp

Creating RegExp Object:

Set objReg=CreateObject("vbscript.regexp") m) Internet Explorer

n) Outlook Express

a) Dictionary Object

Dictionary Object that stores data key, item pairs. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a

string, but can be anything except an array.

Creating a Dictionary Object:

Set objDictionary = CreateObject("Scripting.Dictionary")

Dictionary Objects Methods:

Add Method Adds a key and item pair to a Dictionary object Exists Method Returns true if a specified key exists in the Dictionary object, false if it does not. Items Method Returns an array containing all the items in a Dictionary object. Keys Method Returns an array containing all existing keys in a Dictionary object. Remove Method Removes a key, item pair from a Dictionary object. RemoveAll Method The RemoveAll method removes all key, item pairs from a Dictionary object.

Example:

Dim cities Set cities = CreateObject("Scripting.Dictionary") cities.Add "h", "Hyderabad" cities.Add "b", "Bangalore" cities.Add "c", "Chennai"

Dictionary Objects Properties: Count Property Returns the number of items in a collection or Dictionary object. Read-only. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object. Key Property Sets a key in a Dictionary object. Item Property Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write. Examples:

1) Add Elements to a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"

2) Delete All Elements from a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" colKeys = objDictionary.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next objDictionary.RemoveAll colKeys = objDictionary.Keys Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next

3) Delete One Element from a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"

colKeys = objDictionary.Keys

Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next

objDictionary.Remove("Printer 2") colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next

4) List the Number of Items in a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing"

objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" Wscript.Echo objDictionary.Count

5) Verify the Existence of a Dictionary Key

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"

If objDictionary.Exists("Printer 4") Then Wscript.Echo "Printer 4 is in the Dictionary." Else Wscript.Echo "Printer 4 is not in the Dictionary." End If

VBScript Coding Conventions Coding conventions are suggestions are designed to help us write code using VB Script. Coding conventions can include the following:

• Naming conventions for objects, variables, and procedures

• Commenting conventions • Text formatting and indenting guidelines

The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that we and others can easily read and understand the code. Using good coding conventions results in clear, precise, and readable source code that is consistent with other language conventions and is intuitive.

Variable Naming Conventions To enhance readability and consistency, we have to use the following prefixes with descriptive names for variables in our VBScript code.

Subtype Prefix Example ---------------------------------------------Boolean bln blnFound

----------------------------------------------Byte byt bytRasterData ----------------------------------------------------Date (Time) dtm dtmStart ---------------------------------------------------Double dbl dblTolerance ----------------------------------------------------Error err errOrderNum ----------------------------------------------------Integer int IntQuantity

----------------------------------------------------Long lng lngDistance ----------------------------------------------------Object obj objCurrent ----------------------------------------------------Single sng sngAverage ----------------------------------------------------String str strFirstName

-----------------------------------------------------

Object Naming Conventions: The following table lists recommended conventions for objects you may encounter while programming VBScript.

Object type

Prefix

Example

--------------------------------------------------3D Panel pnl pnlGroup

--------------------------------------------------Animated button ani aniMailBox

--------------------------------------------------Check box chk chkReadOnly

--------------------------------------------------Combo box cbo cboEnglish

--------------------------------------------------Command button cmd cmdExit

--------------------------------------------------Common dialog dlg dlgFileOpen

--------------------------------------------------Frame fra fraLanguage

---------------------------------------------------

Image

img

imgIcon

--------------------------------------------------Label lbl lblHelpMessage

--------------------------------------------------Line lin linVertical

--------------------------------------------------List Box lst lstPolicyCodes

--------------------------------------------------Spin spn spnPages

--------------------------------------------------Text box txt txtLastName

---------------------------------------------------

Slider

sld

sldScale

---------------------------------------------------

Code Commenting Conventions

All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation.

Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, especially through reference arguments, should also be described at the beginning of each procedure.

Procedure header comments should include the following section headings. For examples, see the "Formatting Your Code" section that follows.

Section Heading

Comment Contents

Purpose: What the procedure does (not how).

Assumptions: List of any external variable, control, or otherelement affects this procedure.

whose state

Effects: List of the procedure's effect on each external variable, control, or other element.

Inputs: Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.

Return Values: Explanation of the value returned.

Remember the following points:

•Every important variable declaration should include an inline comment describing the use of the variable being declared.

•Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details.

•At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.

Formatting the Code Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few suggestions:

• Indent standard nested blocks four spaces.

• Indent the overview comments of a procedure one space.

• Indent the highest level statements that follow the overview comments four spaces, with each nested block indented an additional four spaces.

The following code adheres to VBScript coding conventions. '********************************************************* ' Purpose: Locates the first occurrence of a specified user ' in the UserList array.

' Inputs: strUserList(): the list of users to be searched. ' strTargetUser: the name of the user to search for.

' Returns: The index of the first occurrence of the strTargetUser ' ' in the strUserList array. If the target user is not found, return -1.

'********************************************************* Function intFindUser (strUserList(), strTargetUser) Dim i ' Loop counter. Dim blnFound ' Target found flag intFindUser = -1 i = 0 ' Initialize loop counter Do While i <= Ubound(strUserList) and Not blnFound If strUserList(i) = strTargetUser Then blnFound = True ' Set flag to True intFindUser = i ' Set return value to loop count

End If i = i + 1 ' Increment loop counter Loop End Function VB Script Properties VB Script Classes Creating Classes

Classes aren't a new concept in scripting. JavaScript, JScript, and other scripting languages have supported classes or similar elements for years. However, VBScript 5.0 is the first version of VBScript to support classes.

To use classes in your VBScript code, you first need to obtain VBScript 5.0 by downloading the appropriate self-executable file from the Microsoft Developer Network (MSDN) Web site (http://msdn.microsoft.com/scripting) or by installing Microsoft Internet Explorer (IE) 5.0. Then you need to understand what a VBScript class is and learn how to declare, define, initialize, and instantiate a class.

VBScript Classes

VBScript 5.0 supports two types of objects: COM objects and Class objects (typically referred to as simply classes). VBScript COM objects have basic subtypes, such as an Integer or String. VBScript classes have an abstract subtype that encapsulates data and the functions to work with that data. You can think of a VBScript class as having a souped-up subtype that provides you with more computing power and flexibility. (Other differences exist between these two types of objects. For more information, see the Web-exclusive sidebar "How VBScript Classes and COM Objects Differ" on the Win32 Scripting Journal Web site at http://www.winntmag.com/ newsletter/scripting.

You can use classes to describe complex data structures. For example, if your application tracks customers and orders, you can define two classes for them, each with a unique set of internal data (typically called properties) and functions (typically called methods). You can then manage customers and orders as if they were native VBScript subtypes. More important, because you assign a class its properties and methods (i.e., its programming interface), you have an object-oriented tool to improve VBScript applications.

Declaring a Class

You use the Class statement to declare a class. This statement's syntax is:

Class name ' Properties and methods go here. End Class where name is the name you give that class. You declare the properties and methods for your class between the Class and End Class clauses.

For example, suppose you want to create the VBScript class FileList, which Listing 1 contains. This class manages those files in a folder that meet a filename specification that you provide. You create this class by first specifying the keyword Class followed by the class' name Class FileList. Next, you declare the class' properties and methods. FileList has two properties (FileSpec and FolderPath) and one method (Search).

Declaring the FileSpec Property

The FileSpec property holds the filename specification. For example, the filename specification might be C:\*.*. You want users to be able to freely read and write values to this property, so you declare FileSpec as an external, or public, variable with the Public statement

Public FileSpec

You can use a public variable in any script, not just the script in which you created the variable. However, if you use a public variable, you have no control over the value that users assign to the variable and no control over the value that the variable returns. Thus, you can't use public variables to hold values that you need to validate.

Declaring the FolderPath Property

The FolderPath property holds the full path to the folder containing the files. After a user sets a folder path, you need to validate that the folder exists, which means you can't use a public variable. Instead, you need to store the folder path in an internal, or private, variable and use two public property procedures to read and write to that variable. (Public property procedures are wrappers that hide the code that gets and sets the values of private variables.)

Prefixing a private variable with the m_ string is a common scripting convention. For example, the private variable for the FolderPath property is m_folderPath. To declare m_folderPath, you use the Private statement

Private m_folderPath

Procedures and variables that have the Private qualifier aren't visible outside the class. In addition, private variables apply only to the script in which you created them.

After you declare m_folderPath, you need to declare the two public property procedures that you'll use to read and write to that variable. The first procedure to declare is the Property Get procedure, which returns the values of properties. The second procedure is the Property Let procedure, which assigns values to properties.

To declare the Property Get procedure, you use the Property Get statement

Public Property Get FolderPath FolderPath = m_folderPath End Property where FolderPath is the name of that procedure. By including the Public statement with the Property Get statement, you're making the value that the FolderPath procedure returns available for public reading. Thus, by assigning FolderPath to m_folderPath, you make the value of m_folderPath available for public reading. VBScript Syntax Rules and Guidelines 1) Case-sensitivity: By default, VBScript is not case sensitive and does not differentiate between upper-case and lower-case spelling of words, for example, in variables, object and method names, or constants. For example, the two statements below are identical in VBScript: Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31" browser("mercury").page("find a flight:").weblist("today").select "31" 2) Text strings:

When we enter a value as a text string, we must add quotation marks before and after the string. For example, in the above segment of script, the names of the Web site, Web page, and edit box are all text strings surrounded by quotation marks. Note that the value 31 is also surrounded by quotation marks, because it is a text string that represents a number and not a numeric value. In the following example, only the property name (first argument) is a text string and is in quotation marks. The second argument (the value of the property) is a variable and therefore does not have quotation marks. The third argument (specifying the timeout) is a numeric value, which also does not need quotation marks. Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items, 2000) 3) Variables: We can specify variables to store strings, integers, arrays and objects. Using variables helps to make our script more readable and flexible 4) Parentheses: To achieve the desired result and to avoid errors, it is important that we use parentheses () correctly in our statements. 5) Indentation: We can indent or outdent our script to reflect the logical structure and nesting of the statements. 6) Comments: We can add comments to our statements using an apostrophe ('), either at the beginning of a separate line, or at the end of a statement. It is recommended that we add comments wherever possible, to make our scripts easier to understand and maintain.

7) Spaces:

We can add extra blank spaces to our script to improve clarity. These spaces are ignored by VBScript. VBScript General Examples 1) Write a program for finding out whether the given year is a leap year or not? Dim xyear xyear=inputbox ("Enter Year") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 2) Write a program for finding out whether the given number is, Even number or Odd number? Dim num num=inputbox ("Enter a number") If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 3) Read two numbers and display the sum? Dim num1,num2, sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require msgbox ("Sum is " &sum) 4) Read P,T,R values and Calculate the Simple Interest? Dim p,t, r, si p=inputbox ("Enter Principle") t=inputbox ("Enter Time")

r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest msgbox ("Simple Interest is " &si) 5) Read Four digit number, calculate & display the sum of the number or display Error message if the number is not a four digit number? Dim num, sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10 num=num/10 num= left (num, 3) sum=sum+num mod 10 num=num/10 num= left (num, 2) sum=sum+num mod 10 num=num/10 num= left (num, 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number, you entered is not a 4 digit number" End If 6) Read any Four-digit number and display the number in reverse order? Dim num,rev num= inputbox("Enter a number") If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num,3) rev=rev*10 + num mod 10 num=num/10 num= left(num,2) rev=rev*10 + num mod 10 num=num/10 num= left(num,1)

rev=rev*10 + num mod 10 msgbox "Reverse Order of the number is "&rev Else msgbox "Number, you entered is not a 4 digit number" End If 7) Read 4 subjects marks; calculate the Total marks and grade? a) If average marks Greater than or equal to 75, grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 , then grade is First c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third e) Minimum marks 35 for any subject, otherwise 'no grade fail') Dim e,m,p,c, tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade, Fail" End If End If End If End If 8) Display Odd numbers up to n?

Dim num,n n=Inputbox ("Enter a Vaule") For num= 1 to n step 2 msgbox num Next 9) Display Even numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 10) display natural numbers up to n and write in a text file? Dim num, n, fso, myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting.filesystemobject") set myfile=fso.opentextfile ("E:\gcreddy.txt", 8, true) myfile.writeline num myfile.close Next 11) Display Natural numbers in reverse order up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 12) Display Natural numbers sum up to n? (Using For...Next Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0

For num= 1 to n step 1 sum= sum+num Next msgbox sum 13) Display Natural numbers sum up to n? (using While...Wend Loop) Dim num, n, sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum 14) Display Natural numbers sum up to n? (Using Do...Until...Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 15) Write a Function for Natural Numbers sum up to n? Function NNumCou (n) Dim num, sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 16) Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If 17) Verify weather the entered value is a 10 digit value or not and Numeric value or not? (Using multiple if conditions) Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If len (num) =10 Then

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then Msgbox "It is NOT valid Number " End If 18) Generate interest for 1 to 5 years (for 1 year -7%, 2 years -8%, 3 years-9%, 4 years10%, 5 years -11%) Dim amount, duration, intr amount=inputbox("enter amount") If amount<10000 Then msgbox "low amount" else For duration=1 to 5 If duration=1 Then intr=amount*7/100 msgbox "1 year intrest is: " &intr else if duration=2 Then intr=amount*8/100 msgbox "2 years intrest is: " &intr else if duration=3 Then intr=amount*9/100 msgbox "3 years intrest is: "&intr else if duration=4 Then intr=amount*10/100 msgbox "4 years intrest is: "&intr

else if duration=5 Then intr=amount*11/100 msgbox "5 years intrest is: "&intr else msgbox "invalid data" End If End If End If End If End If Next End If VB Script General Examples

1) Read a value and find size of the value Dim val: val=Inputbox("Enter value for val: ") val_length =Len(val) msgbox "Size of "&val&" is "&val_length

2) Read a value and find whether the value is numeric or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsNumeric(val) If val_type = true Then msgbox "val is Numeric" else msgbox "val is not Numeric" End If 3)'Read a value and find whether the value is Date type data or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsDate(val) If val_type = true Then msgbox "val is Date type data"

else msgbox "val is not date type" End If

4)Read a value and Verify whether the value is 10-digit number or not and started with 9 0r 8. 'Then Display it is a valid mobile number Dim val,val_Length, val_Numeric, val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then msgbox val&" is a valid mobile number " Else msgbox val&" is not a valid mobile number " End If 5) 'Read a mobile number and verify the series 'if it starts with 92478 or 92471 then display it is TataIndicom number 'if it starts with 98490 or 98480 then display it is Airtel number Dim val, val_Length,val_Numeric,val_Series,val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) val_Series=Left(val,5) If val_Numeric=true Then If val_Length=10 and val_Start=9 Then If val_Series = 92478 or val_Series=92471 Then msgbox "It is TataIndicom Number" ElseIf val_Series=98490 or val_Series = 98480 then msgbox "It is Airtel Number"

End If Else msgbox val&" is not a valid mobile number " End If Else msgbox val& " is Invalid data" End If 6) Read a Value and Verify weather the value is started with Alfa bytes or not? (First letter should be Alfa byte) Dim val, val_Asc val=Inputbox("enter a value") val_Asc=Asc(val) Msgbox val_Asc If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then msgbox val&" is an Alphabet" Else msgbox val&" is not an Alphabet" End If 7) Read a value and Verify weather the value is Alfa bytes are not? Dim str, valAsc, flag,i Dim strlen, counter,valsingle counter=0 str=Inputbox("enter a string value") strlen= Len(str) For i=1 to strlen step 1 valsingle=Mid(str,i,1) valAsc=Asc(valsingle) If valAsc>=65 and valAsc<=90 or valAsc>=97 and valAsc<=122Then flag=1 counter=counter+1 Else flag=0 End If

Next msgbox "No.of characters " &counter If counter=strlen and flag=1Then msgbox str&" is an Alphabetic value" Else msgbox str&" is not an Alphabetic value" End If VB Script Glossary of Terms ActiveX control An object that you place on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. The controls have an .ocx file name extension.

ActiveX object An object that is exposed to other applications or programming tools through Automation interfaces. Argument A constant, variable, or expression passed to a procedure. Array A set of sequentially indexed elements having the same type of data. Each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements. ASCII Character Set American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0–127) in the ANSI character set. Automation object An object that is exposed to other applications or programming tools through Automation interfaces. Bitwise comparison A bit-by-bit comparison of identically positioned bits in two numeric expressions.

Boolean expression An expression that evaluates to either True or False. By reference A way of passing the address, rather than the value, of an argument to a procedure. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. By value A way of passing the value, rather than the address, of an argument to a procedure. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed. character code A number that represents a particular character in a set, such as the ASCII character set. Class The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior. Class module A module containing the definition of a class (its property and method definitions). Collection An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary. Comment Text added to code by a programmer that explains how the code works. In Visual Basic Scripting Edition, a comment line generally starts with an apostrophe ('), or you can use the keyword Rem followed by a space. Comparison operator A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (=). Is is also a comparison operator, but it is used exclusively for determining if one object

reference is the same as another. Constant A named item that retains a constant value throughout the execution of a program. Constants can be used anywhere in your code in place of actual values. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. For example: Data ranges Each Variant subtype has a specific range of allowed values: Subtype Range Byte 0 to 255. Boolean True or False. Integer -32,768 to 32,767. Long -2,147,483,648 to 2,147,483,647. Single -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. Double -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Date January 1, 100 to December 31, 9999, inclusive. Object Any Object reference. String Variable-length strings may range in length from 0 to approximately 2 billion characters. Date expression Any expression that can be interpreted as a date. This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999. Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899. Date literal Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format. For example, #12/31/99# is the date literal that represents December 31, 1999, where English-U.S. is the locale setting for your application.

In VBScript, the only recognized format is US-ENGLISH, regardless of the actual locale of the user. That is, the interpreted format is mm/dd/yyyy. Date separators Characters used to separate the day, month, and year when date values are formatted. Empty A value that indicates that no beginning value has been assigned to a variable. Empty variables are 0 in a numeric context, or zero-length in a string context. Error number A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the Err object. When combined with the Name property of the Err object, this number represents a particular error message. Expression A combination of keywords, operators, variables, and constants that yield a string, number, or object. An expression can perform a calculation, manipulate characters, or test data. Intrinsic constant A constant provided by an application. Because you can't disable intrinsic constants, you can't create a user-defined constant with the same name. Keyword A word or symbol recognized as part of the VBScript language; for example, a statement, function name, or operator. Locale The set of information that corresponds to a given language and country. A locale affects the language of predefined programming terms and locale-specific settings. There are two contexts where locale information is important: • The code locale affects the language of terms such as keywords and defines localespecific settings such as the decimal and list separators, date formats, and character sorting order. • The system locale affects the way locale-aware functionality behaves, for example,

when you display numbers or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system. Nothing The special value that indicates that an object variable is no longer associated with any actual object. Null A value indicating that a variable contains no valid data. Null is the result of: • An explicit assignment of Null to a variable. • Any operation between expressions that contain Null. Numeric expression Any expression that can be evaluated as a number. Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number. Object type A type of object exposed by an application, for example, Application, File, Range, and Sheet. Refer to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on) for a complete listing of available objects. pi Pi is a mathematical constant equal to approximately 3.1415926535897932. Private Variables that are visible only to the script in which they are declared. Procedure A named sequence of statements executed as a unit. For example, Function and Sub are types of procedures. Procedure level Describes statements located within a Function or Sub procedure. Declarations are usually listed first, followed by assignments and other executable code. For example:

Sub MySub() ' This statement declares a sub procedure block. Dim A ' This statement starts the procedure block. A = "My variable" ' Procedure-level code. Debug.Print A ' Procedure-level code. End Sub ' This statement ends a sub procedure block. Note that script-level code resides outside any procedure blocks. Property A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled. Public Variables declared using the Public Statement are visible to all procedures in all modules in all applications. Run time The time when code is running. During run time, you can't edit the code. Run-time error An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation. Scope Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public is visible to all procedures in all modules. Variables declared in procedures are visible only within the procedure and lose their value between calls. SCODE A long integer value that is used to pass detailed information to the caller of an interface member or API function. The status codes for OLE interfaces and APIs are defined in FACILITY_ITF. Script level

Any code outside a procedure is referred to as script-level code. Seed An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences. String comparison A comparison of two sequences of characters. Unless specified in the function making the comparison, all string comparisons are binary. In English, binary comparisons are case-sensitive; text comparisons are not. String expression Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, or a string variable. Type library A file or component within another file that contains standard descriptions of exposed objects, properties, and methods. Variable A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope. Variable names: • Must begin with an alphabetic character. • Can't contain an embedded period or type-declaration character. • Must be unique within the same scope. • Must be no longer than 255 characters. QTP Certification QTP Certification Sample Questions

1) How many tabs are there in Test Settings (File->Settings) window A) 5 B) 6 C) 7 D) 8 2) 'Browser navigation timeout' is in which tab of Test Settings (File->Settings) window? A) Properties B) Resources C) Web D) Web Settings 3) Identify the tabs in the Test Settings (File->Settings) window A) Properties, Run, Resources, Parameters, Environment, Web, Recovery B) Properties, Run, Resources, Parameters, Environment, Web Settings,Recovery C) Properties, Run Options, Resources, Parameters, Environment, Web, Recovery D) Properties, Run, Resources, Input Parameters, Environment, Web, Recovery 4) 'Generate Script' is in which tab of Test Settings (File->Settings) window A) Properties B) Resources C) Web D) Recovery 5) For each object and method in an Expert View statement, a corresponding row exists in the Keyword View. A) True B) False C) There is some problem with the statement. D) None of above 6) The following are the four main columns in the Keyword view A) Item, Operation, Value, Comments B) Item, Operation, Value, Documentation

C) Item, Operation, Property, Documentation D) Number, Operation, Value, Documentation 7) You can work on one or several function libraries at the same time. A) True B) False 8) You can insert additional steps on the test objects captured in the Active screen after the recording session. A) True B) False 9) The Active Screen enables you to parameterize object values and insert checkpoints A) True B) False 10) A QTP user can increase or decrease the active screen information saved with the test. A) True B) False 11) The toolbar enables you to view the details of an individual action or the entire test flow is: A. Testing toolbar B. None of the above C. Action toolbar D. Test Pane 12) The key that is used to Start/End analog recording mode ? A. F3 B. SHIFT+ALT+F3 C. CTRL+SHIFT+F3 D. F10 13) QuickTest supports virtual object for analog or low-level recording.

A. False B. True 14) To use a specific property to identify your object, but that property is not listed in the properties list. Then how do you identify that object? A. Add the specific property to the list B. Use the Default property C. Use some other property to identify your object 15) The checkpoint used to check the alt attribute exists for all relevant objects (such as images) is A. Database CheckPoint B. Accessibility checkpoint C. Bitmap checkpoint D. Standard checkpoint 16) Bitmap checkpoint is supported in VB environment. A. True B. False 17) Can we parameterize the checkpoints properties? A. No B. Yes 18) What is the shortcut key that is used for a Standard Checkpoint? A. F12 B. F2 C. F10 D. F7 19) Can we change name of checkpoint? A. No B. Yes 20) To compare the values of the specified property during a run session with the

values stored for the same test object property within the test. A. Checkpoint B. All the above C. Output Value D. Compare the object property 21) You will use which recording mode for an object not recognized by QuickTest? A. Low-Level Recording Mode B. Normal recording Mode C. Analog Mode 22) The statement that calls the recorded analog file is: A. RunAnalog B. CallAnalog C. ExecuteAnalog 23. An action can be called by other tests or actions is: A. Call Action B. Split Action C. Reusable Action 24. You can replace the page in your Active Screen tab: A. False B. True 25. QuickTest adds a checkpoint statement in the Expert View as: A. Check Checkpoint B. Checkpoint 26. A Checkpoint checks that a text string is displayed within a defined area in a Windows application is: A. Accessibility B. Text Area C. Standard D. Text

27. In ACTIVE X environment, an ACCESSIBILITY checkpoint is supported? A. No B. Yes 28. Can we get the execution time for an action in a Test? A. Yes B. No 29. Can we add external library files in QTP? 1. No 2. Yes 30. The method used to get data from HTML Table is A. GetData(Row,Col) B. GetRowValue(Rowid,Colname) C. GetCellData (Row,Col) 31. The Command used to insert the transactions in test is: A. StartTransaction(Name�), EndTransaction(Name�)B . Services.StartTransaction "Name", Services.EndTransaction "Name" C. StartTransaction.services "Name�, EndTransaction.services "Name" 32. A step in which one or more values are captured at a specific point in your test and stored for the duration of the run session is: A. Output Value B. Checkpoints C. Active Screen 33. QTP can detects an application crash and activate a defined recovery scenario to continue the run session. A. True B. false 34. In Batch Test process, the test list are saved in file format as:

A. *.mtb B. *.mts C. *.mbt D. *.mtr 35. The command used to invoke other application from QTP: A. InvokeApplication B. SystemUtil.Run C. Run D. Both b & c E. Both a & b 36. The command used to retrieve data from excel sheet is A. Set ab = Connection("srcfilepath ") , Set ws = ab.getdata(sheetid) B. Set ab = CreateObject("srcfilepath ") , Set ws = ab.getsheet(sheetid) C. Set ab = GetObject("srcfilepath") , Set ws = ab.worksheets(sheetid) 37. The method that explicitly activates the recovery scenario mechanism is: A. recovery.activate B. enable C. recovery.enable D. activate 38. The method used for sending information to the test results is: A. Reporter.log() B. Reporter.reportevent() C. Reporter.msgbox() D. Reporter.report() 39. To terminate an application that is not responding we use: A. SystemUtil.terminate B. SystemUtil.Stop C. SystemUtil.CloseProcessByName 40. The recovery mechanism does not handle triggers that occur in the last step of a

test: A. false B. True 41. We can add Test object methods, function calls into the Test using: A. Function generator B. Step generator C. Object repository 42. The method that adds to the test while implementing synchronization is: A. Synchronize B. Wait C. WaitProperty D. Pause 43. The mechanism used to identify objects during run session is: A. Recovery scenario B. Smart identification C. Handling object 44. Post-recovery test run options specifies: A. how to continue the run session after QTP identify the event B. errors while running C. recovery scenario during a run session 45. The action that can be called multiple times by the test as well as by other tests is called: A. non-reusable action B. Reusable action C. External action 46. The command used to connect with Database is: A. Createobject(connectivity name�) B. dbconnect(connectivity name) C. open(connectivity name)

D. None of the above 47. The method used to retrieve the folders is: A. FileSystemObject.Getfolder() B. FileSystemObject.selectfolder() C. FileSystemObject.retrievefolder() 48. The method used to compare 2 XML files is: A1. XMLfile1.compare(XMLfile2) B. XMLcompare(file1,file2) C. compare(XMLfile1,XMLfile2) 49. The QTP script files are stored in the extension of: A. *.mts B. *.usr C. *.mtr D. *.vbs 50. The method used to register the user-defined function with test object is: A. setFunc() B. RegisterUserFunc() C. RegisterFunc() 51. The method used to open the specified URL in a browser is: A. openURL() B. navigateURL() C. navigate() 52. The 3 Parameter types available in data driver is: A. DataTable,Environment,Random number B. DataTable,random number,unique C. environment,string,numeric 53. The method added to the test while parameterizing is: A. get Data (variable, dtGlobalSheet)

B. get DataTable(variable, dtGlobalSheet) C. Set Data(variable, dtGlobalSheet) D. Set DataTable(variable, dtGlobalSheet) 54. The length of the array can be get by the method: A. length(array) B. ubound(array) C. count(array) 55. The method used to get the count value of list box or combo box is: A. GetItemsCount B. GetCount C. GetItemCount 56. To retrieve the current the objects in your application during the run session: A. GetVisibleText B. GetROProperty C. SetROProperty D. GetTOProperty 57. The list of test objects and their properties and values are stored in the: A. Object Repository B. Object Identification 58. The method used to continue the test execution after getting run-time error is: 1. On Error Resume Next 2. On Error Raise Next 3. On Error Next 59. 'Browser navigation timeout' is in which tab of Test Settings (File->Settings) window. A) Properties B) Resources C) Web D) Web Settings

60. How many tabs are there in Test Settings (File->Settings) window A) 7 B) 6 C) 5 D) 8 61. Identify the tabs in the Test Settings (File->Settings) window A) Properties, Run, Resources, Parameters, Environment, Web, Recovery B) Properties, Run, Resources, Parameters, Environment, WebSettings,Recovery C) Properties, Run Options, Resources, Parameters, Environment, Web,Recovery D) Properties, Run, Resources, Input Parameters, Environment, Web, Recovery 62. 'Generate Script' is in which tab of Test Settings (File->Settings)window A) Properties B) Web C) Resources D) Recovery 63. The following are the four main columns in the Keyword view A) Item, Operation, Value, Comments B) Item, Operation, Value, Documentation C) Item, Operation, Property, Documentation D) Number, Operation, Value, Documentation 64. For each object and method in an Expert View statement, acorresponding row exists in the Keyword View. A) True B) False C) There is a problem with the statement. D) None of above 65. You can work on one or several function libraries at the same time. A) True B) False

66. You can insert additional steps on the test objects captured in the Active screen after the recording session. A) True B) False 67) The Active Screen enables you to parameterize object values andinsert checkpoints A) True B) False 68) A QTP user can increase or decrease the active screen informationsaved with the test. A) True B) False 69) The Information pane provides a list of............. in the test: A) Semantic errors B) Syntax errors C) Common errors D) Logic errors 70) When we switch from Expert view to the Keyword view, QTPautomatically checks for syntax errors in the test and shows them in theinformation pane. A) True B) False 71) If the information pane is not open, QTP automatically opens it incase a syntax error is detected. A) True B) False 72) . ..................... provides a list of the resources that arespecified in your test but cannot be found. A) Missing pane

B) Missing Resources pane C) Resources pane D) Missing Items pane 73) Whenever you open a test or a function library, QTP automaticallychecks for the availability of specified resources. A) True B) False 74) The Data Table does not assists you in parameterizing your test. A) True B) False 75) Tabs in the Debug Viewer pane are: A) Watch, Variables, Debug B) Watch, Data, Command C) Watch, Variables, Command D) View, Variables, Command 76) . ............... tab enables you to view the current value of anyvariable or VBScript expression. A) Watch B) VIew C) Locate D) Current 77) The .... tab displays the current value of all variables that havebeen recognized up to the last step performed in the run session. A) View B)Variables C) Locate D) Current 78) The .........tab enables you to run a line of script to set ormodify the current value of a variable or VBScript object in your testor function library.

A) View B) Variables C) Command D) Current 79) Panes in QTP can have one of the following states—docked or floating. A) True B) False 80) Which of the following statement is True: A) QuickTest enables you to open and work on one test at a time B) QuickTest enables you to open and work on two tests at a time C) QuickTest enables you to open and work on predefined number of testsat a time D) QuickTest enables you to open and work on nine test at a time 81) Which of the following statement is True: A) You can open and work on two function libraries simultaneously B) You can open and work on multiple function libraries simultaneously C) You can open and work on nine function libraries simultaneously D) You can open and work on one function library at a time 82) You can open any function library, regardless of whether it isassociated with the currently open test. A) True B) False 83) You can work with multiple documents (test, component, or application area, function libraries) using the...... dialog box A) Panes B) Display C) Show D) Windows

Sign up to vote on this title
UsefulNot useful