Upload
narasimha-murthy-ks
View
544
Download
1
Embed Size (px)
Citation preview
QTP Complete Reference
QTP Guide Step by Step QTP Guide for beginners as well as advanced learners. It explains QTP Tool fundamentals and features in detailed manner. It covers QTP tool window keyelements, QTP test process, Recording and Running tests,Enhancing tests, Debugging Tests, Analyzing Test Results and Reporting Defects.
It describes QTP important features like Step Generator, Sychronization, Parameterization, Recovery scenarios and Object Identification Configuration.
An overview on Test Automation
QTP Basic features
Add-in Manager
Key elements of QTP
Test Pane
QTP Commands
QTP Test Process
Recording Tests
Keyword Driven Methodology
Test Object Model
Object Repository
Object Identification Configuration
QTP Test Methods
Data Table MethodsDescriptive Programming
Enhancing Tests
Inserting Checkpoints
Inserting Output values
Parameterization
Synchronization
Inserting Transaction Points
Step Generator
Adding Comments
Inserting Flow Control Statements
Debugging Tests
Running/Executing Tests
Analyzing Test Results & Reporting
Reporting Defects
Actions
FunctionsEnvironment Variables
Regular Expressions
Virtual Object Configuration
Batching Testing
Recovery Scenarios
File System Operations
Database connections
Automation Object Model
Dynamic Handling of Object Repositories
QTP Performance Tips****************************************
QTP Scripting QTP Tests in VB Script orientation provides a real-time approach on Scripting. It explains Flat file scripts, Excel Scripts, GUI Scripts, Web scripts, Database scripts and xml scripts with syntax and examples.****************************************
File System Scripts
Flat File Scripts
Database Scripts-I
Database Scripts-II
Excel Scripts
GUI Scripts
Web Scripts
Web Scripts -II
QTP Real-time Script Examples
Network Administration
System Administration
Power point Scripts
Word Scripts
XML Scripts
QTP Skills
Error Handling in QTP****************************
VB Script for QTPIt explains VB Script in QTP orientation, It covers all most all VB Script Fundamentals and Features.It describes, Variables, constants declarations, usage of operators, VB Script flow control statements, Procedures, Coding conventions, Regular Expressions, File system Operations, Database Operations etc..****************************************
Scripting Languages Vs Programming Languages
VB Script Fundamentals & Features
Comments
VB Script Variables
VB Script Data Types
VB Script Operators
Input/Output Operations
VB Script Constants
VB Script Conditional Statements
Loop through Code
VB Script Statements
VB Script Procedures
VB Script Errors
VB Script Built-In Functions
User Defined Functions
Regular Expressions
VB Script Methods
VB Script Objects
VB Script Coding Conventions
VB Script Classes
VB Script Keywords
VB Script syntax rules and guidelines
VB Script General Examples
VB Script General Examples-II
VB Script Glossary******************************************
QTP Framework This section provides concepts on How to implement Automation Framework. It explains about Automation Infrastructure development, Resources creation, Driver script creation, Initialization script creation etc.It describes data driven framework, keyword driven framework and Hybrid framework in detailed manner. It also provides Test estimations, Approvals, Reporting, Organizing and maintaining frameworks.
**********************************************
QTP Interview Questions
QTP Model ResumesThis section provides, Resume preparation guidelines for fresher as well as experienced. It provides some model QTP Resumes for
reference.
QTP Job NewsThis section Provides QTP Job news weekly. Information can be collected by Employers, Consultants and employees. QTP Professionals can use this information and their resumes directly to Employer's and consultants mail ids.
QTP CertificationThis section provides HP QTP Certification guidelines and model Questions, It useful for QTP test professionals for preparing Certification exam.
QTP Training ProgramsThis section provides information on variou QTP Training programs like QTP Basics program for beginners, Advanced program for working people, QTP Framework, and VB Script for QTP that conducted by gcreddy.com
Manual Testing Documents This section Provides link to our another website gcreddy.net, there you can get Manual Testing Information like, Software Testing Guide, Manual Testing Interview question and answers, Test management guidelines, Test planning, Test design and other documents.*******************************************
Quality CenterThis Section Provides Quality Center Fundamentals and features; Site Administration, Creating Domains, Projects, and Users. Creating Requirements, Designing Manual & Automated Tests, Executing Manual and Automated Tests and Entering defects. Sending Defects directly from QTP Result window.**********************************************************
LoadRunner
This section provides LoadRunner tool Fundamentals and Features; Vuser generator, Controller, Load Generator, Analysis and LoadRunner Interview Questions.*********************************************************
QTP Other Topics This section provides QTP Related articles and other information like, challenges in Test Automation using QTP, Migrating Test scripts from old version to New version, QTP trends, enhancements, New release information, Browser compatibility issues etc..
QTP Software Download Link
SQL Server Guide
Software Testing Documents Documents on Unit Testing, Web Testing, Software Testing Artifacts, Software Test Process Etc.. QTP Basic Features• QTP was Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007.
• QTP is an Object Based Testing Tool.
(Object based means; QTP Follows Test Object Model for Performing Testing operations. Based on either Test Objects or Automation Objects or Utility Objects only, we can automate test operations)
(LoadRunner is a Protocol based Test Tool)• QTP is for Functional and Regression Testing.
(Basically QTP is a Functional and Regression Test tool but we can use it for little bit Compatibility Testing and Performance Testing)• It follows Keyword Driven Approach.
(Keyword Driven Approach means; Keywords, example: Commands, functions, methods, statements etc.. are used for creating Test scripts)• It supports Windows Operating Environment only.
(QTP basically depends on User Interface to automate test operations and it is not depends on server side interactions, where as LoadRunner depends on server side Operations, so HP developed LoadRunner for Windows as well as UNIX versions)
• It supports GUI based (Graphical user interface) and Web based Applications Automation, does not support CUI (Command user interface) Applications.
• It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages with respect to license.)
• It has adapted Microsoft Visual Basic Scripting edition for programming and Excel like spread sheet for Data driven testing.
Tools support for QTP:------------------------------• VB Script for Scripting (for implementing programming logic)
• VB Script engine integrated in QTP, so apart from scripting features we can use File system, Excel, word, Adodb etc. Object models from QTP.
• SQL (Structured query language) engine integrated in QTP, so we can use SQL Statements in QTP to perform Database Operations
• Excel like spread sheet integrated in QTP for performing Data driven Testing
• We can install MS Script Debugger with QTP for Debugging Test scripts.
• QTP uses XML format for Test results, Environment variables and for exporting object repositories.-------------------------------------------------------
• QTP can be integrated with other Tools like WinRunner and Quality Center.
• QTP can be used for user interface (UI) test case automation and some limited (Non UI) Test case automation like File system operations and Data base operations.
• It was derived from Astra QuickTest (mother tool of QTP).
• It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers like Mozilla and AOL, opera Etc apart from IE.
• QTP is a Desktop Application (I-Tier/Stand alone).
• QTP developed in .NET Technology.
• Since it is Stand-alone Application, It doesn't have Database, It stores resources as files (Internal and External). We can't share qtp services from one machine to another, but we can share resources(Ex: Object Repository files, Function Libraries, Environment variable files, Recovery scenario files etc...)
QTP has two types of License;
• Seat or Node locked License,
• Concurrent or float license.
• We have to use Seat license from fixed system/machine and Concurrent License, we can use from any system but one user at a time. If we want multiple concurrent licenses that we can purchase.
• QTP has UNI code support.
Version History of QuickTest Professional
• Astra QuickTest (Mother tool of QTP) 1.0 to 5.0
* QTP derived from Astra QuickTest and influenced by WinRunner.
Quick Test Professional
• 5.6 – Nov 2002
• 6.5 – 2003
• 8.0 – 2004
• 8.2, 8.3 –2005
• 9.0,9.1-2006
• 9.2- 2007 Mercury Interactive
• 9.5 –2008 H.P
• 10.00 –2009 January
• 11.00 –2010** (It is Latest Version) Overview----------------------------------------------------------------a) Disadvantages of Manual Testing 1) Huge Amount of Human Resources as well as Environment (Test lab)
2) Time taking process
3) Less Accuracy
4) Tideness
b) Advantages of Test Automation
1) Fast 2) Reliable 3) Accurated 4) Reusable 5) Repeatable 6) Comprehensive
c) Draback of Test Automation
1) Expensive 2) Technical expertise 3) 100% Automation not Posible
d) Types of Test Tool
Business cla Technical cla--------------------------------------Vendor Tools Functional & Regression Test toolsOpensource Performance/Load/stress Test toolsIn-House Test Management Tools Defect Management Tools Security Unit Test tools Etc...------------------------------------------------------------------------
I) Basic Features of QTP------------------------------------------------------------------------- a) QTP Supporting Environments 1) UI (GUI/Windows and Web) 2) Only Windows (Clien side and Server side) b) Version History QTP derived from Astra QuickTest(1.0....5.0)
5.6 2002 (Nov) 6.5 2003 8.0 2004 8.2 2005 9.0, 9.1 2006 9.2 2007 9.5 2008--------HP 10.0 2009 (Jan)
c) QTP License(Seat/Node Locked and Concurent/Float) c) QTP IDE 1) QTP Features Ex: Recording, Checkpoints, Object Repository etc... 2) Integrated Tools (HP) Ex: Password Encoder, Test Batch Runner, Test Result Dletion Tool etc.. 3) Integrated Tools (Others) Ex: Spread sheet, VB Script Engine, SQL Engine, MS Script Debugger
d) Key elements of QTP 1) Test Pane 2) Active Screen 3) Data Table 4) Debug Viewer 5) Information Pane 6) Missing Resources 7) QTP Commands
--------------------------------------------------------------------------- II) QTP Test Process---------------------------------------------------------------------------
Manual Test Process (STLC) Vs QTP Test Process-----------------------------------------------------------------I) Planning I) Planning a) Analyzing Requirements a) Analyzing the AUT b) Test Strategy Implentation b) selecting/Creating Test case for Automation c) Test estimations c) Test Estimations & Approvals d) team formation d) Automation framework Implementation
e) Risk Analysys e) QTP Tool Settings Configuration f) Configuration management g) Defining Test Environment h) Test Plan Documentation --------------------------------------------------------------------------------II) Test Design IIA) Creating the Basic Tests
a) Understanding & Analyzing Reqs a) Repository based Test creationb) Generating Test Scenarios 1) Recording (Local Repository)c) Test case Documentation 2) Keyword driven methodology (Shared Repository) b) Descriptive Programming 1) Static Programming 2) Descriptive Programming IIB) Enhancing Tests a) Adding Comments b) Inserting Checkpoints c) Inserting Output values d) Inserting Transaction points e) Generating steps thru Step Generator f) Inserting Flow Control Statements g) Synchronization h) Parameterization i) Calling Functions / Actions j) Using Regular expressions k) Using Environment Variables l) Using Automation Objects (using Object Models) ----------------------------------------------------------------------------------III) Test Execution IIIA) Debugging Tests (Optional)----------------------------------------------------------------------------------a) Forming Test Batches/suites a) Step by step executionb) Test Environment setup b) Watching Variablesc) Test Execution c) Locating & Isolating Errorsd) Analyzing Test Resultsd) Defect Reporting e) Defect Tracking III B) Running Tests f) Re & Regression Testing a) Single Test Rung) Test status Reporing b) Batch Testingh) Test Logs c) Executing Tests thru Frameworki) Final Regression d) Scheduled execution
e) Analyzing Results f) Result Reporing g) Defect Reporing h) Regression Testing-------------------------------------------------------------------------------------------IV) Test Closure IV) Test Closure-----------------a) evaluating Exit Criteria a) Sending Test scripts & Resources to Customerb) Collecting all facts from Test Activities b) Maintaning Tests & Resouce filesc) sending Test Delivarables to Customer c) Improvement Suggessionsd) Improvement Suggessions for QA Process ---------------------------------------------------------------------------------------------
III) Creating Tests / Test Scripts
------------------------------------------------------------------------------------------
1) Repository based Test Design a) Recording (Local repository) b) Keyword Driven methodology (Shared repository)
2) Descriptive Programming a) Static Programming b) Dynamic programming
Recording Tests---------------- a) Recording Process b) Recording Modes i) Normal Recording ii) Analog Recording iii) Low Level Recording c) Running Process
Object Repository:------------------ a) Object and Types of Object
i) Run-time Objects ii) Test Object Model iii) Utility Objects iv) Automation Objects
b) Types of Object Repository i) Local Repository ii) Shared Repository c) Operations on Object Repository i) Adding Objects ii) Renaming Objects iii) Deleting Objects iv) Exporting Local Objects v) Merging Repositories vi) Associating Repositories to an Action vii) View Options viii) Exporting Objects to XML/Importing Objects from XML iX) Defining New Test Objects X) Spying Objects
d) Object Identification Configuration i) Normal identification 1) Mandatory properties 2) Assistive properties ii) Smart Identification (Optional) 1) Base Filter properties 2) Optional Filter properties iii) Ordinal Identifier 1) Location 2) Index 3) Creation Time (Only for web Application)
Keyword driven methodoly:-------------------------
a) Creating Shared Object Repositories b) Associating Repositories to an Action c) Creating tests manually i) Thru Expert View ii) Keyword View iii) generate steps thru Step Generator
Descriptive programming:------------------------
a) Static programming
i) identifying Unique Properties for Objects ii) Creating Constants iii)Creating Library file for constants iv) associating Library files / loading Library files during run-time v) Using Constants, generating Tests
b) Dynamic Programming i) Creating Collection Objects ii) Entering Properties Information into Collection Objects iii) Using Collection Objects, generating tests c) Handling Dynamic Objects using Regular expressions
d) Handling Duplicate/Similar Objects using Index property------------------------------------------------------------------------------------------------------
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 anymodifications 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 ScreenIt 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 TableIt 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 ViewerIt 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) InformationThis pane shows syntax errors automatically during saving the test.Navigation: view menu> information
7) QTP CommandsQTP Commands are available in 3 ways.
1). Menu options2). Tool Bar options3). 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 non-recordable 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 Commands
QTP Commands are available in 3 ways.
1.Menu options2.Tool Bar options3.Short cut keys (for Some important operations only)
File menu: Through file menu user can create, save tests, open existing tests, export tests in zip format.
Command Function
New > Test Creates a new test.
New > Business Component
Creates a new business component.
New > Scripted Component
Creates a new scripted component.
New > Application Area Creates a new application area.
New > Function Library Creates a new function library.
Open > Test Opens an existing test.
Open > Business/Scripted Component
Opens an existing business or scripted component.
Open > Application Area Opens an existing application area.
Open > Function Library Opens an existing function library.
Close Closes the active function library.
Close All Function Libraries
Closes all open function libraries.
Quality Center Connection Opens the Quality Center Connection dialog box, enabling you to connect to
a Quality Centerproject.
Quality Center Version Control
Provides a sub-menu of options for managing versions of QuickTest assets in Quality Center. The sub-menu is available only when you are connected to version-control enabledQuality Center project.
Save Saves the active document.
Save As Opens the relevant Save dialog box so you can save the open document.
Save Test with Resources Saves a standalone copy of the current test together with its resource files.
Save All Saves all open documents.
Enable Editing Makes read-only function libraries editable.
Export Test to Zip File Creates a zip file of the active document.
Import Test from Zip File Imports a document from a zip file.
Convert to Scripted Component
Converts a business component to a scripted component.
Print Prints the active document.
Print Preview Displays the Keyword View as it will look when printed and enables you to modify the
page setup.
Settings Opens the Settings dialog box, enabling you todefine settings for the open document. (Not relevant for function libraries)
Process Guidance Management
Opens the Process Guidance Management dialog box, enabling you to manage the list of processes that are available in QuickTest.
Associate Library '<Function Library Name>' with '<Document Name>'
Associates the active function library with the open document. (Available only from function libraries)
Recent Files Lists the recently viewed files.
Exit Closes the QuickTest session.
Edit Menu: It provides editing options and renaming, deleting and splitting actions.
Command Function
Undo Reverses the last command or deletes the last entry you typed.
Redo Reverses the most recent operation of the Undo command.
Cut Removes the selection from your document.
Copy Copies the selection from your document.
Paste Pastes the selection to your document.
Delete Deletes the selection from your document.
Copy Documentation to Clipboard
Copies the content of the Documentation column of the Keyword View, enabling you to paste it in an external application.
Action > Split Action Separates an action into two sibling actions or into parent-child nested actions.
Action > Rename Action Changes the name of an action.
Action > Delete Action Enables you to remove the selected call to the action, or delete the action and its calls from the active test.
Action > Action Properties Enables you to specify options, parameters, and associated object repositories for a stored action.
Action > Action Call Properties
Enables you to specify the number of run iterations according to the number of rows in the Data Table, and to define the values of input parameters and the storage location of output parameters.
Step Properties > Comment Properties
Opens the Comment Properties dialog box for a comment step. Available only when the selected step is a comment.
Step Properties > ObjectProperties
Opens the Object Properties dialog box for a selectedobject. Available only when the selected step contains a test object.
Step Properties > Checkpoint Properties
Opens the relevant Checkpoint Properties dialog box for a selected object. Available only when the selected step is a checkpoint step.
Step Properties > Output Value Properties
Opens the relevant Output Value Properties dialog box for a selected object. Available only when the selected step is an output value step.
Step Properties > Report Properties
Displays the Report Properties dialog box for a report step. Available only when the selected step is aReporter.ReportEvent step.
Find Searches for a specified string.
Replace Searches and replaces a specified string.
Go To Moves the cursor to a particular line in the test.
Bookmarks Creates bookmarks in your script for easy navigation.
Advanced > Comment Block
Comments out the current row, or selected rows.
Advanced > Uncomment Block
Removes the comment formatting from the current or selected rows.
Advanced > Indent Indents the step according to the tab spacing
defined inthe Editor Options dialog box.
Advanced > Outdent Outdents the step (reduces the indentation) according to the tab spacing defined in the Editor Options dialog box.
Advanced > Go to Function Definition
Navigates to the definition of the selected function.
Advanced > Complete Word
Completes the word when you type the beginning of a VBScript method or object.
Advanced > Argument Info
Displays the syntax of a method.
Advanced > Apply "With" to Script
Generates With statements for the action displayed in the Expert View, and enables IntelliSense within Withstatements.
Advanced > Remove "With" Statements
Converts any With statements in the action displayed in the Expert View to regular (single-line) VBScript statements.
Optional Step Inserts an optional step (a step that is not required to successfully complete a run session).
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 non-recordable 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 optionsThrough this menu we can start normal recording, analog recording and Low levelrecording.
Through this menu we can stop recoding, running and also we run tests.
Command Function
Record Starts a recording session.
Run Starts a run session from the beginning or from the line at which the session was paused.
Stop Stops the recording or run session.
Run Current Action Runs only the active action.
Run from Step Starts a run session from the selected step.
Maintenance Run Mode Starts a run session during which the Maintenance Run Mode wizard opens for steps that failed because an object was not found in the application(if applicable).
Update Run Mode Starts a run session to update test objectdescriptions and other options (if applicable).
Analog Recording Starts recording in Analog Recording mode.
Low Level Recording Starts recording in Low Level Recording mode.
Record and Run Settings Opens the Record and Run Settings dialog box, enabling you to define browser preferences for recording and running your test.
Process Guidance List Lists the processes that are available for the current document type and for the currently loaded QuickTest add-ins, enabling you to open them.
Results Enables you to view results for a test run session.
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.
Command Function
Object Repository Opens the Object Repository window, which displays a tree containing all objects in the current test or component.
Object Repository Manager Opens the Object Repository Manager dialog box, enabling you to open and modify multiple sharedobject repositories.
Associate Repositories Opens the Associate Repositories dialog box, enabling you to manage the object repository associations for the test.
Map Repository Parameters Opens the Map Repository Parameters dialog box, enabling you to map repository parameters, as needed.
Recovery Scenario Manager Opens the Recovery Scenario Manager dialog box.
Associated Function Libraries Lists the function libraries associated with the active document, enabling you to open them.
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.
Command Function
Options Opens the Options dialog box, enabling you to modify
global testing options.
View Options Opens the Editor Options dialog box, enabling you to customize how tests and function libraries are displayed in the Expert View and Function Library windows.
Check Syntax Checks the syntax of the active document.
Object Identification Opens the Object Identification dialog box, enabling you to specify how QuickTest identifies a particular test object.
Object Spy Opens the Object Spy dialog box, enabling you to view the native properties and operations of any object in an open application, as well as the test object hierarchy, identification properties, and operations of the test object that QuickTest uses to represent that object.
Web Event Recording Configuration
Opens the Web Event Recording Configuration dialog box, enabling you to specify a recording configuration level. (Relevant for tests only)
Data Driver Opens the Data Driver dialog box, which displays the default Constants list for the action. (Relevant for tests only)
Change Active Screen Replaces the previously recorded Active Screen with the selected Active Screen. (Relevant for tests only)
Virtual Objects > New Virtual Object
Opens the Virtual Object Wizard, enabling you to teach QuickTest to recognize an area of your application as a standard test object.
Virtual Objects > Virtual Object Manager
Opens the Virtual object Manager, enabling you to manage all of the virtual object collections defined on your computer.
Customize Opens the Customize dialog box, which enables you to customize toolbars and menus, and create new menus.
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 Process7 Stages of QTP Testing Process
1) Planning
o Analyzing the AUTo Automation Test Plan Generationo Automation Framework Implementationo Generating/Selecting Test cases for Automationo Collecting Test Datao QTP Tool Settings Configuration
2) Generating Tests
o Recordingo Keyword driven methodologyo Descriptive Programming
3) Enhancing Tests
o Inserting Checkpointso Inserting Output valueso Adding Commentso Synchronizationo Parameterizationo Inserting Flow Control Statementso Calling User defined functions and/or Reusable Actionso Generating Steps though Step Generatoro Inserting Transaction Pointso Regular Expressions
4) Debugging Tests
o Debug Commands & Break Pointso Step by step executiono Watching Variableso Changing values of variables
5) Running Tests
o Normal Executiono Batch Executiono Through AOM Scriptingo Tests Running through frameworko Scheduled Execution
6) Analyzing Results
o QTP Result windowo Defining our own Resultso Exporting Resultso Deleting Results
7) Reporting Defects
o Manual Defect Reportingo Tool based Defect Reportingo Working with Quality Center----------------------------------------------------------- Types of Statements in QTP Test / Test Script
i) Declarations (Variables and constants)
Dim x, y, zConst 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 StatementsEx1: SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"**It launche the ApplicationEx2:SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","http://www.icicibank.com/"
vii) VB script other statements
Examples:
Option ExplicitWait (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 ObjectRepository.
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 Scriptsi) 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 state2.Select Record Option3.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 OK6.Perform actions on AUT7.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 normaloperations 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 mode2.Automation >Analog RecordingORUse 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 option3.Automation>Analog Recording4.Analog Recording Settings Dialog box opens
(In this Dialog box two options available.
1.Record relative to the screen2.Record relative to the following window)
(If we select first option QTP records User operations with respect to Desktop co-ordinates.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 actions7.Stop Recording
iii) Low Level Recording
It records some operations on Non-supported environments apart from Normaloperations.
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 mode2.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 option3)Automation> Low Level Recording4)Perform options on AUT5)Stop Recording6)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
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 ourorganization. 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 applicationtesters 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 atransaction 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.Object RepositoryObject 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 objects2. Test objects3. Utility objects4. 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 points4. 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, dictionaryobject 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 objectsa. 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 onlyo Default object typeso All objects typeso 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 objectclasses 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 ofthe 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 isproviding 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
Object Identification ConfigurationOverview:
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 properties2) Assistive properties
b) Smart identification
1) base filter properties2) optional filter properties
c) Ordinal identifier 1) location2) index3) 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 theseproperties 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 propertiesat 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 FilterProperties 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
QTP Methods / Operations1) Activate Method
It activates dialog boxes/Windows
Syntax: Object hierarchy. Activate Ex:Dialog(“Login”).ActivateWindow(“Flight Reservation”).Activate
2) Click MethodIt clicks on an object (Buttons)Syntax: Object hierarchy. ClickEx:Dialog(“Login”).Winbutton(“ok”).click
3) Close MethodIt closes the window,Dialog box, Browser window etc.Syntax: Object hierarchy. CloseEx:Window(“Flight Reservation”).CloseBrowser(“Browser”).Close
4) Dblclick It Double clicks the object.
5) Set MethodIt can be used in three ways.a. For setting the value of an edit boxSyntax: Object Hierarchy. SET “Value”Ex: Dialog (“Login”).WinEdit(“Agent Name”).Set “asdf”
b. Selecting a Radio ButtonSyntax: Object Hierarchy. SetEx: Window("Flight Reservation").WinRadioButton("Business").Set
c. Selecting/Deselecting check boxesSyntax:object Hierarchy.Set “ON/off”Ex: Window ("Flight Reservation"). Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
6) 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
7) GetVisibletext: It returns Text from the specified area.Syntax: Variable =object hierarchy.getvisibletextEx:x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleTextmsgbox x
8) 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
9) Navigate Method:It opens a specified URL in the Browser.Syntax: object hierarchy.navigate “URL”Ex: Browser("Yahoo!").Navigate http://www.google.co.in/
10) Getitemscount: It returns number of items in a combobox.Syntax: Variable=object hierarchy.getitemscountEx: x=Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCountmsgbox x
11) Getcontent: It returns all items from a combobox.Syntax: variable=object hierarchy.GetContentEx: x=Window("Flight Reservation").WinComboBox("Fly From:").GetContentmsgbox x
12) Exist property: It checks whether the object is available or not.Syntax: Object hierarchy.exist(time in seconds)Ex: Window("Flight Reservation").Exist(5)
Data Table Methods
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.GetSheetCountmsgbox 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”, “DestinationSheet”
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 tableto 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 andSettings\gcr\Desktop\gcreddy.xls",1,3Rows_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" elseReporter.ReportEvent micFail,"res","Failed"Login="Login Operation Failed"Datatable("Result",3)=Login
Dialog("Login").Dialog("Flight Reservations").WinButton("OK").ClickDialog("Login").WinButton("Cancel").ClickEnd If
If Window("Flight Reservation").Exist(3)Then Window("Flight Reservation").Close End ifNext
Descriptive Programming
Descriptive ProgrammingEntering / 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 Programming2. 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").Activate3) 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 Objects2. text, attached text - Property names3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the Object4. 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").SyncBrowser("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).ActivateDialog(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.CreateSet oAgent=description.CreateSet oPassword=description.CreateSet oOk=description.Create
Entering Properties Information into Objects
oLogin("text").value="Login"oLogin("width").value=320oLogin("height").value=204oAgent("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).ActivateDialog(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
Inserting CheckpointsCheck 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. Standard check point2. Text check point3. Text area check point4. Bit map check point5. Data base check point6. Accessibility check point7. XML Check point (from Application)8. XML Check point (from Resource)9. Page check point
10. Image checkpoint11. 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 thesecheckpoints through standard checkpoint.
1. Standard Checkpoint:
It checks object property values. We can use this checkpoint for checking anyproperty 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. Through expert view,b. Through keyword view,c. 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) If an item is available, according to W3C rules then Pass.c) 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 (fromapplication)> 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. Standard output value
2. Text output value
3. Text area output value
4. Database output value
5. XML output value (From Application)
6. 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 definedarea 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
statementsmanually >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
XMLdocuments.
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
XMLdocuments.
Navigation:
Insert menu >output value> XML output value from resource > browse path of the
XML file > click ok > select elements >click ok.
ParameterizationPassing 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 Statements2. Dynamic Test Data Submission3. Through Data Table4. 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 mandatoryWindow("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ordernoWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").ClickNext
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 3Agent =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").ActivateDialog("Login").WinEdit("Agent Name:").Set AgentDialog("Login").WinEdit("Agent Name:").Type micTabDialog("Login").WinEdit("Password:").SetSecure passwordDialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseNext
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:
i) Generate the basic test>open data table(View>Data Table)
ii) 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.)
iii) Run the test.
Example:
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.
i). Creating a Test Database: open MS Access (or we can use any other database).
ii) Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension.
iii)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.
iv) Entering Data into Tables: Select table>enter the data.
v)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, myfileSet fso=createobject("scripting.filesystemobject")Set myfile=fso.opentextfile("d:\trigun.txt",1)
myfile.skiplineWhile myfile.atendofline <> truex=myfile.readlineS=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").ActivateDialog("Login").WinEdit("Agent Name:").Set s(0)Dialog("Login").WinEdit("Agent Name:").Type micTabDialog("Login").WinEdit("Password:").SetSecure S(1)Dialog("Login").WinEdit("Password:").Type micReturnWindow("Flight Reservation").CloseWend
Fetching Test Data directly from Excel Sheets
Fetching Test Data directly from Databases
Option explicitDim con,rsSet 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",condo until rs.eof=trueSystemUtil.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").ActivateDialog("Login").WinEdit("Agent Name:").Set rs.fields ("agent")Dialog("Login").WinEdit("Agent Name:").Type micTabDialog("Login").WinEdit("Password:").SetSecure rs.fields("password")Dialog("Login").WinEdit("Password:").Type micReturnWindow("Flight Reservation").Closers.movenextloop--------------------------------------Using Dictionary Object for Parameterization
Set inputdata=CreateObject("Scripting.Dictionary")
inputdata.Add "Agent","gcreddy"inputdata.Add "Password","mercury"
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set inputdata("Agent")Dialog("Login").WinEdit("Password:").Set inputdata("Password")Dialog("Login").WinButton("OK").Click
SynchronizationIt 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 inbetween 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>okNote: 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.SyncEx: 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 process3) 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 PointsQTP 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").ActivateDialog("Login").WinEdit("Agent Name:").Set "naga"Dialog("Login").WinEdit("Password:").SetSecure "4baf50f18b0ae0d5f5425fe760653e96da50bde7"Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").Activateservices.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 secondsExample: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").ActivateDialog("Login").WinEdit("Agent Name:").Set "naga"Dialog("Login").WinEdit("Password:").SetSecure "4baf50f18b0ae0d5f5425fe760653e96da50bde7"Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").ActivateET=TimerTT=ET-STmsgbox TT
Note: here ST, ET and TT are variables, you can take any variable, I used:ST for Start TransactionET for End transactionTT 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 context-sensitive options and entering the required values. In the Step Generatordialog box we can define steps that use:
Test object operations (tests only)Utility object operationsCalls to library functions (tests only), VBScript functions, and internal script functionsFor 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 conditionalstatement. 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 inour 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 StepGenerator.
We can open the Step Generator from the Keyword View, Expert View, or Active Screen.
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
aretaking 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) Passb) Failc) Doned) 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 objectReportEvent-MethodmicPass-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 DefectsQTP 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 managementmanual, 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.
ActionsAction: 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 actions2) Re usable actions3) 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 okSteps:
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 action2. 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,xval="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,xval="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,xval="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,xval="Hyderabad"x=StrReverse(val)
msgbox x 'Output dabaredyH
val="001"x=StrReverse(val)msgbox x 'Output: 100
val=1002x=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,xstr1="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=100str2=100x=StrComp(str1,str2,1)msgbox x 'Output 0
str1=100str2=101x=StrComp(str1,str2,1)msgbox x 'Output -1
6) Lcase function
Coverts Upper case values into Lower case
Dim val,xval="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,xval="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 (Fromnumber 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 & appDialog("Login").ActivateDialog("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 addicon (+) > enter variable name & Value > click ok (like this we can create numberof 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 objectso For parameterizing a stepo 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 aregular 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, 0-9, _).
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 RegExpobjRE.Global = TrueobjRE.IgnoreCase = FalseobjRE.Pattern = WScript.Arguments(0)
For Each objFile In colFiles bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End IfNext
2) Match Content in a File against a Regular ExpressionstrFileName = "E:\gcreddy.txt"Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(strFileName)strFileContents = objTS.ReadAllWScript.Echo "Searching Within: "WScript.Echo strFileContentsobjTS.Close
Set objRE = New RegExpobjRE.Global = TrueobjRE.IgnoreCase = FalseobjRE.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.ValueNext
Virtual Object ConfigurationVirtual 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 optionso Entire Parent hierarchyo 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 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 executableapplication->Next ->Select Recovery Operation [Keyboard, Mouse Operation,Close Application Process, function Call, Restart, Microsoft Windows] ->Next ->Ifyou want to check Add another operation else uncheck->Next ->Next ->EnterScenario Name ->Next->Select Option ->Finish ->Close ->Save the scenario inspecified 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 “PopupWindow” as Trigger event ->Next ->Click on Hand Icon ->Show unwantedwindow with Hand icon ->Next ->Next ->Select function call as Recovery
Operation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browsethe .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next ->Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed toNext step, Proceed to Next Action, Proceed to next test iteration, Restart current testrun, Stop the Test Run] ->Next ->Enter Scenario Name ->Next ->Select Option ->Finish ->Save the scenario with “.qrs” ->Record required Recovery Operation [Clickok, 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 Errorcan be raised.
Navigation :
Resources Menu ->Recovery Scenario Manager ->New ->Next ->Select “TestrunerrorWindow” as Trigger event ->Next ->select any error o ->Next ->Next ->Select function call as RecoveryOperation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browsethe .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next ->Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed toNext step, Proceed to Next Action, Proceed to next test iteration, Restart current testSelect Option ��Next ��Enter Scenario Name ��Next ��run, Stop the Test Run] ��Record required Recovery Operation [ClickSave the scenario with “.qrs” ��Finish ��Click RunSave the library file ��ok, Click Cancel] take the script into function ��
(iv) Object State.
The property values of an object in your application matchspecified values. You can specify property values for each object in thehierarchy.
Navigation:
Resources Menu -> Recovery Scenario Manager -> New -> Next -> Select “Object stateWindow” 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 RecoveryOperation -> Next [Open Notepad -> Save empty file with .vbs extension] -> Browsethe .vbs fie path -> Next -> Uncheck Add another Recovery Operation -> Next ->Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed toNext step, Proceed to Next Action, Proceed to next test iteration, Restart current testrun, Stop the Test Run] -> Next-> Enter Scenario Name -> Next -> Select Option ->Finish -> Save the scenario with “.qrs” -> Record required Recovery Operation [Clickok, 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.filesystemobjectand 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 folderDim fso, strFolderstrFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok"Set fso=createobject("scripting.filesystemobject")fso.CreateFolder(strFolder)
2) Create a folderDim fso, strFolderstrFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok"Set fso=createobject("scripting.filesystemobject")If fso.FolderExists(strFolder) Then msgbox "Folder already exists" elsefso.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, myFieldSet objFso=CreateObject("Scripting.FileSystemObject")Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-AppendmyFile.SkipLine
Do Until myFile.AtEndOfStreammyLine=myFile.ReadLinemyField=Split(myLine,",")SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0)Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1)wait 2Dialog("text:=Login").WinButton("text:=OK").ClickWindow("text:=Flight Reservation").CloseLoopmyFile.CloseSet objFso=Nothing
for more Examples visit:
File System Scripts
Flat File Scripts
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=Your_Username;Pwd=Your_Password;"
Trusted connection:
"Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Trusted_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;InitialCatalog=Your_Database_Name;Integrated Security=SSPI;" SQL OleDbConnection .NET stringsStandard 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;InitialCatalog=Your_Datab
ase_Name;Integrated Security=SSPI;" SQL SqlConnection .NET stringsStandard 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;Password=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=True;"
MS Access connection strings
MS Access ODBC connection stringsStandard Security:"Driver= {MicrosoftAccessDriver(*.mdb)};DBQ=C:\App1\Your_Database_Name.mdb;Uid=Your_Username;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 stringsOpen 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; DataSource=\\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 stringsOpen 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 stringsOpen connection to MySQL database:"Provider=MySQLProv;Data Source=Your_MySQL_Database;User Id=Your_Username; Password=Your_Password;"
Oracle connection strings
Oracle ODBC connection stringsOpen connection to Oracle database using ODBC"Driver= {Microsoft ODBCforOracle};Server=Your_Oracle_Server.world;Uid=Your_Username;Pwd=Your_Password;" Oracle OLE DB & OleDbConnection (.NET framework) connection stringsOpen 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_Password;"
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:1) Write an AOM Script to launch QTP Tool, Execute Tests and to close the QTP Tooloption explicitDim qtAppSet qtApp=createobject ("Quicktest.Application")qtApp.LaunchqtApp.visible=True
qtApp.open "C:\Documents and Settings\admin\My Documents\login"qtApp.Test.RunqtApp.Test.Close
qtApp.open "C:\Documents and Settings\admin\My Documents\open order"qtApp.Test.RunqtApp.Test.Close
qtApp.quitSet qtApp=Nothing
Note: AOM Script can be used in Automation framework as an Initialization script.'------------------------------------------------------------------ 2) Write an AOM script to execute series of tests
Dim objFso,objQtp,myFile,i,gcreddy
Set objQtp = CreateObject("Quicktest.Application")objQtp.Visible = TrueobjQtp.Launch
Set objFso =CreateObject("Scripting.FileSystemObject")Set myFile = objFso.OpenTextFile("C:\Users\Chinni\Desktop\Test\gcreddy.txt")i =1Do Until myFile.AtEndOfStream =Truetesturl = myFile.ReadLine
objQtp.Open gcreddyobjQtp.Test.RunobjQtp.Test.Closei = i+1Loop
objQtp.QuitSet objQtp = Nothing
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").ActivateDialog("Login").WinEdit("Agent Name:").Set "sudhakar"Dialog("Login").WinEdit("Password:").Set "mercury"Dialog("Login").WinButton("OK").Clickpos=RepositoriesCollection.Find(RepPath)RepositoriesCollection.Remove(pos)RepositoriesCollection.RemoveAll
QTP Scripting QTP Tests in VB Script orientation provides a real-time approach on Scripting. Itexplains Flat file scripts, Excel Scripts, GUI Scripts, Web scripts, Database scripts and xml scripts with syntax and examples.
File System Scripts1) Create a Folder
Option ExplicitDim objFSO, objFolder, strDirectorystrDirectory = "D:\Gcreddy"Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFolder = objFSO.CreateFolder(strDirectory)
2) Delete a Folder
Set oFSO = CreateObject("Scripting.FileSystemObject")oFSO.DeleteFolder("E:\Gcreddy")
3) Copying Folders
Set oFSO=createobject("Scripting.Filesystemobject")oFSO.CopyFolder "E:\gcr", "C:\jvr", True
4) Checking weather the folder available or not, if not creating the folder
Option ExplicitDim objFSO, objFolder, strDirectorystrDirectory = "D:\Gcreddy"Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) ThenSet objFolder = objFSO.GetFolder(strDirectory)msgbox strDirectory & " already created "elseSet objFolder = objFSO.CreateFolder(strDirectory)end if
5) Returning a collection of Disk Drives
Set oFSO = CreateObject("Scripting.FileSystemObject")Set colDrives = oFSO.DrivesFor Each oDrive in colDrivesMsgBox "Drive letter: " & oDrive.DriveLetterNext
6) Getting available space on a Disk Drive
Set oFSO = CreateObject("Scripting.FileSystemObject")Set oDrive = oFSO.GetDrive("C:")MsgBox "Available space: " & oDrive.AvailableSpace
Flat File Scripts Computer File System It is a feature of the Operating System, used to Create/Modify/view/delete Drives, Folders and Files
OS DistributionOperating System and Other Utilities FileSystemObject
VBScript has Provided FileSystemObject to perform file system operations through scripting
Dim objFso'Creating an Automation Object in File System class, that can be used to performOperations on Computer File SystemSet objFso=CreateObject("scripting.FileSystemObject")
1) Creating a File
Dim objFsoSet objFso=CreateObject("scripting.FileSystemObject")objFso.CreateTextFile ("E:\Gcreddy.txt")objFso.CreateTextFile ("E:\Gcreddy.doc")objFso.CreateTextFile ("E:\Gcreddy.xls")objFso.CreateTextFile ("E:\Gcreddy.pdf")
Note: We can Create other files also, but they act as Text/Flat FilesSet objFile = objFSO.CreateTextFile("E:\Gcreddy.txt")
2) Checking weather the File is available or not, if not creating the File
strDirectory="E:\"strFile="Gcreddy.txt"Set objFSO = CreateObject("Scripting.FileSystemObject")If objFSO.FileExists(strDirectory & strFile) ThenSet objFolder = objFSO.GetFolder(strDirectory)ElseSet objFile = objFSO.CreateTextFile("E:\Gcreddy.txt")End if
3) Reading Data character by character from a Flat File
Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1)Do Until objFile.AtEndOfStreamstrCharacters = objFile.Read(1)msgbox strCharactersLoop
4) Reading Data line by line from a Flat File
Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1)Do Until objFile.AtEndOfStreamstrCharacters = objFile.Readlinemsgbox strCharactersLoop
5) 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:
'gcr.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, myFieldSet objFso=CreateObject("Scripting.FileSystemObject")Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-AppendmyFile.SkipLine
Do Until myFile.AtEndOfStreammyLine=myFile.ReadLinemyField=Split(myLine,",")SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0)Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1)wait 2Dialog("text:=Login").WinButton("text:=OK").ClickWindow("text:=Flight Reservation").CloseLoopmyFile.CloseSet objFso=Nothing
6) Writing data to a text file
Dim Stuff, myFSO, WriteStuff, dateStampdateStamp = Date()Stuff = "I am Preparing this script: " &dateStampSet myFSO = CreateObject("Scripting.FileSystemObject")Set WriteStuff = myFSO.OpenTextFile("e:\Gcreddy.txt", 8, True)WriteStuff.WriteLine(Stuff)WriteStuff.CloseSET WriteStuff = NOTHINGSET myFSO = NOTHING
7) Delete a text file
Set objFSO=createobject("Scripting.filesystemobject")Set txtFilepath = objFSO.GetFile("E:\gcr.txt")txtFilepath.Delete()
8) Checking weather the File is available or not, if available delete the File
strDirectory="E:\"strFile="gcr.txt"Set objFSO = CreateObject("Scripting.FileSystemObject")If objFSO.FileExists(strDirectory & strFile) ThenSet objFile = objFSO.Getfile(strDirectory & strFile)objFile.delete ()End if
9) Comparing two text files
Dim f1, f2f1="e:\Gcreddy1.txt"f2="e:\Gcreddy2.txt"Public Function CompareFiles (FilePath1, FilePath2)Dim FS, File1, File2Set FS = CreateObject("Scripting.FileSystemObject")If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size ThenCompareFiles = TrueExit FunctionEnd IfSet File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)CompareFiles = FalseDo While File1.AtEndOfStream = FalseStr1 = File1.ReadStr2 = File2.ReadCompareFiles = StrComp(Str1, Str2, 0)If CompareFiles <> 0 ThenCompareFiles = TrueExit DoEnd IfLoopFile1.Close()File2.Close()End FunctionCall Comparefiles(f1,f2)If CompareFiles(f1, f2) = False ThenMsgBox "Files are identical."Else
MsgBox "Files are different."End If
10) Counting the number of times a word appears in a file
sFileName="E:\gcr.txt"sString="gcreddy"Const FOR_READING = 1Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatchesSet oFso = CreateObject("Scripting.FileSystemObject")Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)sReadTxt = oTxtFile.ReadAllSet oRegEx = New RegExpoRegEx.Pattern = sStringoRegEx.IgnoreCase = bIgnoreCaseoRegEx.Global = TrueSet oMatches = oRegEx.Execute(sReadTxt)MatchesFound = oMatches.CountSet oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothingmsgbox MatchesFound
11) Read a CSV File Using Database Techniques
On Error Resume Next
Const adOpenStatic = 3Const adLockOptimistic = 3Const adCmdText = &H0001
Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")
strPathtoTextFile = "C:\Databases\"
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & strPathtoTextFile & ";" & _ "Extended Properties=""text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM PhoneList.csv", _ objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF Wscript.Echo "Name: " & objRecordset.Fields.Item("Name") Wscript.Echo "Department: " & _ objRecordset.Fields.Item("Department") Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension") objRecordset.MoveNextLoop
12) Read a Text File into an Array
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")Set objTextFile = objFSO.OpenTextFile _ ("e:\gcreddy.txt", ForReading)
Do Until objTextFile.AtEndOfStream strNextLine = objTextFile.Readline arrServiceList = Split(strNextLine , ",") Wscript.Echo "Server name: " & arrServiceList(0) For i = 1 to Ubound(arrServiceList) Wscript.Echo "Service: " & arrServiceList(i) NextLoop
13) 'Calculate size of a Text file
Dim objFso, File1,File2File1="C:\Documents and Settings\1 RIGHATWAY\Desktop\xyz.txt"Set objFso=CreateObject("Scripting.FileSystemObject")x= objFso.GetFile(File1).SizeMsgbox x& " Bytes"
14) 'Test Requirement: Open 1 to 10 orders in Flight Reservation , Capture Customer names and Export into a Text file
'Test Flow:'Login Operation'Open Order Operation and form the Loop to open 1 to 10 Orders'Capture Cusomer names using GetROProperty Method'Create File system Object and Open the Text file using the Object and Export Cusomer names'----------------------------------------------------------------------------Option ExplicitDim Order_Number, Customer_Name, objFso, myFileSet objFso=CreateObject("Scripting.FileSystemObject")Set myFile= objFso.CreateTextFile ("C:\Documents and Settings\1 RIGHATWAY\Desktop\abcNew.txt",2)myFile.WriteLine "Cusomer Names"myFile.WriteLine "--------------------"If Not Window("Flight Reservation").Exist(3) ThenSystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set "asdf"Dialog("Login").WinEdit("Password:").SetSecure "4c48590870466b8dc050bbd24e816890c747ccf8"Dialog("Login").WinButton("OK").ClickEnd IfFor Order_Number= 1 to 10 step 1Window("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_NumberWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").ClickCustomer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text")wait (2)myFile.WriteLine Customer_NameNextmyFile.CloseSet objFso=Nothing
15)'******************************************************'Test Requirement: Capturing all Buttons Names from the Login Dialog box and exporting to a Text file
'Author: G C Reddy
'Date of Creation: 13-08-2010
'Pre-requasites:'gcr.txt
'Test Flow:'Creating an Automation Object in FileSystem class'Opening the External Test Data file using the Object'Creating Collection object and Capturing Button Names using the Object'Writing Button Names to an External Text file'********************************************************
Dim objFso, myFile, oButton, Buttons, TotButtonsSet objFso=CreateObject("Scripting.FileSystemObject")Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",2) '1 for Read, 2-Write & 8-AppendmyFile.WriteLine "Button Names"myFile.WriteLine "----------"Set oButton=Description.Create
oButton("micclass").value="WinButton"SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Set Buttons=Dialog("text:=Login").ChildObjects(oButton)TotButtons=Buttons.Count
For i= 0 to TotButtons-1 myButton=Buttons(i).GetRoProperty("text")myFile.WriteLine myButtonNext
myFile.CloseSet objFso=Nothing
16) Delete a Text file if it is an empty file Dim objFso, FilePathFilePath="C:\Documents and Settings\gcreddy\Desktop\abc.txt"Set objFso=CreateObject("Scripting.FileSystemObject")FileSize=objFso.GetFile(FilePath).Size'Msgbox FileSize
If FileSize=0 ThenobjFso.DeleteFile(FilePath) End If
Set objFso=Nothing
Database Scripts-I1) Get Test Data From a Database and use in Data Driven Testing (through Scripting)
Dim objCon, objRs'Creating an automation object in database connection class, it is used forconnecting to databases.Set objCon=CreateObject("Adodb.Connection")'Creating an automation object in database record set class, it is used forperforming operations on database tables(records).Set objRs= CreateObject("Adodb.Recordset")'Establishing connection string for Ms-Access database.objCon.Provider=("Microsoft.Jet.oledb.4.0")objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Flights.mdb"objRs.Open "Select * from Login", objCon
Do Until objRs.EOF=TrueSystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set objRs.Fields("Agent")Dialog("Login").WinEdit("Password:").Set objRs.Fields("Pwd")Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseobjRs.MoveNextLoopobjRs.CloseobjCon.CloseSet objCon=NothingSet objRs=Nothing
2) Exporting Data from a Database to an Excel Sheet
1) Dim con,rs2) Set con=createobject("adodb.connection")3) Set rs=createobject("adodb.recordset")4) con.provider="microsoft.jet.oledb.4.0"5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.mdb"6) rs.open"select*from Login",con7) Set ex=createobject("Excel.Application")8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\MyDocuments\Gcreddy.xls")9) Set b=a.worksheets("sheet1")10) i=111) Do While Not rs.EOF12) b.cells (i,1).value=rs.fields("agent")13) b.cells(i,2).value=rs.fields("password")14) rs.movenext15) i=i+116) Loop17) a.save18) a.close
3) Exporting Data from a Database to a Text file Dim objCon,objRs,ObjFso,myFile,myData,rc,rSet objCon=createobject("Adodb.connection")
Set objRs=createobject("Adodb.Recordset")set objFso=createobject("Scripting.Filesystemobject")Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\MyDocuments\gcreddy.txt",8)objcon.provider=("Microsoft.jet.oledb.4.0")objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb"objrs.open "select * from login",objConr=1Do until objRs.EOFa=objRs.Fields ("Agent")b=objRs.Fields ("Pwd")myFile.Writeline a &","& br=r+1objRs.MoveNextLoopmyFile.CloseobjCon.Close
4) Connecting to a SQL Sever database
Const adOpenStatic = 3Const adLockOptimistic = 3
Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open _"Provider=SQLOLEDB;Data Source=atl-sql-01;" & _"Trusted_Connection=Yes;Initial Catalog=Northwind;" & _"User ID=fabrikam\kenmyer;Password=34DE6t4G!;"
objRecordSet.Open "SELECT * FROM Customers", _objConnection, adOpenStatic, adLockOptimistic
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
5) Open a Database Using a DSN
Const adOpenStatic = 3Const adLockOptimistic = 3
Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open _"Northwind;fabrikam\kenmyer;34ghfn&!j"
objRecordSet.Open "SELECT * FROM Customers", _objConnection, adOpenStatic, adLockOptimistic
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
6) Open Two Recordsets
Const adOpenStatic = 3Const adLockOptimistic = 3
Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")Set objRecordSet2 = CreateObject("ADODB.Recordset")
objConnection.Open _"Provider= Microsoft.Jet.OLEDB.4.0; " & _"Data Source=inventory.mdb"
objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _objConnection, adOpenStatic, adLockOptimistic
objRecordSet.MoveFirst
objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _objConnection, adOpenStatic, adLockOptimistic
objRecordSet2.MoveFirst
Do Until objRecordset.EOFWscript.Echo objRecordset.Fields.Item("ComputerName")
Wscript.Echo objRecordset.Fields.Item("OSName")objRecordSet.MoveNextLoop
Do Until objRecordset2.EOFWscript.Echo objRecordset2.Fields.Item("DriveName"), _objRecordset2.Fields.Item("DriveDescription")objRecordSet2.MoveNextLoop
objRecordSet.CloseobjRecordSet2.CloseobjConnection.Close
7) Searching a Database Using String Criteria
Const adOpenStatic = 3Const adLockOptimistic = 3
Set objConnection = CreateObject("ADODB.Connection")Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open _"Provider = Microsoft.Jet.OLEDB.4.0; " & _"Data Source = eventlogs.mdb"
objRecordSet.Open "SELECT * FROM EventTable " & _"WHERE Type = 'Error'", objConnection, adOpenStatic, _adLockOptimistic
objRecordSet.MoveFirst
Wscript.Echo "Number of records: " & objRecordset.RecordCount
objRecordSet.CloseobjConnection.Close
Database Scripts-II1) Insert Data into a database table using Database Command Object
Dim objCon,objComSet objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")objCom.ActiveConnection=objCon
objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"objCom.Execute
objCon.CloseSet objCom=NothingSet objCon=Nothing
2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object
Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,iSet objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"
Set objCom=Createobject("ADODB.Command")objCom.ActiveConnection=objCon
Datatable.AddSheet("input")Datatable.ImportSheet "C:\gcreddy.xls",1,"input"intRowcount=Datatable.GetSheet("input").GetRowCountMsgbox intRowcountFor i=1 to intRowcount step 1 DataTable.SetCurrentRow(i) strEmpName= DataTable.Value(1,"input") intEmpNo= DataTable.Value(2,"input") intEmpSal= DataTable.Value(3,"input")objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")"objCom.Execute
Next
objCon.CloseSet objCom=NothingSet objCon=Nothing
3) Fetch data from a database, and compare with expected data in Excel file.----------Dim objCon, objRs, objExcel, myFile, mysheetSet objCon=CreateObject("Adodb.Connection")Set objRs= CreateObject("Adodb.Recordset")Set objExcel=CreateObject("Excel.Application")Set myFile=objExcel.Workbooks.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\TestData2.xls")Set mySheet=myFile.Worksheets("Sheet1")Rc=mySheet.usedrange.rows.count'Msgbox RcobjCon.Provider=("Microsoft.Jet.oledb.4.0")objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Comp.mdb"objRs.Open "Select EMPName from Employee", objCon
Do Until objRs.EOF=Truex=objRs.Fields("EMPName") For j= 2 to Rcy=mySheet.cells(j,"A")
If x=y Then Reporter.ReportEvent micPass,"Res","Name: "& y &" Available"' Else'Reporter.ReportEvent micFail,"Res","Name: "& y &" Not Available"
End If Next objRs.MoveNextLoopobjExcel.QuitSet objExcel=NothingobjRs.Close
objCon.CloseSet objRs=NothingSet objCom=Nothing
QTP Database Script Examples-----------------------------------------------------------------------------1) Data Driven Testing for Login Operation by Fetching Test Data directly From a Database
Option ExplicitDim objConnection, objRecordSet'Creating an Automation Object in Database Connection Class, that can be used to connect to DatabasesSet objConnection=CreateObject("Adodb.Connection")'Creating an Automation Object in Database RecordSet Class, that can be used to Perform Operations on Database Tables (Records)Set objRecordSet=CreateObject("Adodb.RecordSet")'Establishing Connection String for MS Access DatabaseobjConnection.Provider=("Microsoft.Jet.OLEDB.4.0")objConnection.Open "C:\Documents and Settings\bannu\Desktop\gcreddy.mdb"'Fetching Test Data using RecordSet ObjectobjRecordSet.Open "Select * From Login",objConnection
Do Until objRecordSet.EOF=TrueSystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").Winedit("attached text:=Agent Name:").Set objRecordSet.Fields("Agent")Dialog("text:=Login").Winedit("attached text:=Password:").Set objRecordSet.Fields("Password")Wait 2Dialog("text:=Login").Winbutton("text:=OK","width:=60").ClickWindow("text:=Flight Reservation").CloseobjRecordSet.MoveNextLoop
objRecordSet.CloseobjConnection.Close
Set objRecordSet=Nothing
Set objConnection=Nothing
2) Write Data to a Database Table
Dim objConnection, objCommandSet objConnection=CreateObject("Adodb.Connection")Set objCommand=CreateObject("Adodb.Command")objConnection.Provider=("Microsoft.ACE.OLEDB.12.0")objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb"
objCommand.ActiveConnection=objConnection
objCommand.CommandText ="Insert into Login values (8,'Chennai','Mercury')"objCommand.Execute
objConnection.CloseSet objCommand=NothingSet objConnection=Nothing
-----------------------------------------------------3) Write Multiple Sets of Data to a Database Table
Dim objConnection, objCommandDim objExcel, objWorkBook, objWorksheet
Set objExcel=CreateObject("Excel.Application")Set objWorkBook=objExcel.Workbooks.Open ("C:\Documents and Settings\Test class\Desktop\data1.xls")Set objWorkSheet=objWorkBook.Worksheets("Sheet1")
Set objConnection=CreateObject("Adodb.Connection")Set objCommand=CreateObject("Adodb.Command")
objConnection.Provider=("Microsoft.ACE.OLEDB.12.0")objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb"
objCommand.ActiveConnection=objConnectionRows_Count=objWorkSheet.Usedrange.Rows.CountFor i= 2 To Rows_Count Step 1SNO=objWorkSheet.Cells(i,"A")
Agent=objWorkSheet.Cells(i,"B")Password=objWorkSheet.Cells(i,"C")objCommand.CommandText ="Insert into Login values ('"&SNO&"','"&Agent&"','"&Password&"')"objCommand.ExecuteNextobjWorkBook.CloseobjExcel.QuitSet objExcel=NothingobjConnection.CloseSet objCommand=NothingSet objConnection=Nothing
---------------------------------------------------------
4) Export Data from a Database Table to an Excel file (2nd Sheet)
Option ExplicitDim objConnection, objRecordsetDim objExcel, objWorkbook, objWorksheet, i Set objConnection = Createobject ("Adodb.Connection")Set objRecordset = Createobject ("Adodb.Recordset")
Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:\Documents and Settings\Test class\Desktop\data1.xls")Set objWorksheet = objWorkbook.Worksheets("Sheet2")
objWorksheet.cells(1,"A") = "Agents"objWorksheet.cells(1,"B") = "Password"
objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0")objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb"
objRecordset.Open "Select Agent, Password from Login", objConnection
i = 2 'RowsDo Until objRecordset.EOF
objWorksheet.cells(i, "A") = objRecordset.Fields("Agent")objWorksheet.cells(i, "B") = objRecordset.Fields("Password")i = i + 1
objRecordset.MoveNextLoop
objWorkbook.SaveobjWorkbook.CloseobjExcel.QuitSet objExcel = Nothing
objRecordset.CloseobjConnection.Close
Set objRecordset = NothingSet objConnection = Nothing
----------------------------------------------------5) Export Data from a Database Table to a Text file
Option ExplicitDim objConnection, objRecordsetDim objFso,myFileSet objConnection = Createobject ("Adodb.Connection")Set objRecordset = Createobject ("Adodb.Recordset")
Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\data1.txt",2)
myFile.WriteLine "Agent "&" Password"myFile.WriteLine "--------------------"
objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0")objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb"
objRecordset.Open "Select Agent, Password from Login", objConnection
Do Until objRecordset.EOF
myFile.WriteLine objRecordset.Fields("Agent")&" ," & objRecordset.Fields("Password")objRecordset.MoveNextLoop
myFile.CloseSet objFso=Nothing
objRecordset.CloseobjConnection.Close
Set objRecordset = NothingSet objConnection = Nothing
------------------------------------------------6) Export Data from a Text File to a Database Table
Option ExplicitDim objConnection, objCommandDim objFso,myFile,myLine,myField,SNO,Agent,PasswordSet objConnection = Createobject ("Adodb.Connection")Set objCommand = Createobject ("Adodb.Command")
Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\dat1.txt",1)objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0")objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb"myFile.SkipLinemyFile.SkipLine
Do While myFile.AtEndOfStream = FALSEmyLine = myFile.ReadLinemyField = Split(myLine,",")SNO = myField(0)Agent = myField(1)Password = myField(2)
objCommand.ActiveConnection = objConnectionobjCommand.CommandText = "Insert into Login2 values('"&SNO&"','"&Agent&"','"&Password&"')"objCommand.Execute
Loop
myFile.CloseSet objFso=Nothing
Set objCommand = NothingobjConnection.Close Set objConnection = Nothing---------------------------------------------------------------
Excel Scripts1) Create an Excel file, enter some data and save the file through VB script?
1) Dim objexcel2) Set objExcel = createobject("Excel.application")3) objexcel.Visible = True4) objexcel.Workbooks.add5) objexcel.Cells(1, 1).Value = "Testing"6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")7) objexcel.Quit
2) Check if the Excel file exists or not, if exists open the file and enter some data , If not Exists create the file and enter some data and save the file through VB script?
Dim objExcel, FilePathFilePath="C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcr.xls"Set objExcel=CreateObject("Excel.Application")set objFso=CreateObject("Scripting.FileSystemObject")objExcel.Visible=True
If Not objFso.FileExists(FilePath) ThenobjExcel.Workbooks.AddobjExcel.Cells(1,1).value="QTP"objExcel.ActiveWorkbook.SaveAs (FilePath)
Elseset myFile= objExcel.Workbooks.Open (FilePath)Set mySheet=myFile.Worksheets("Sheet1")mySheet.cells(1,1).value="QTP"objExcel.ActiveWorkbook.SaveEnd IfobjExcel.QuitSet objExcel=Nothing
3) Data Driven Testing through an External Excel Sheet
1) Set myExcel=Createobject("Excel.Application")2) Set myFile=myExcel.workbooks.open ("C:\Documents andSettings\admin\My Documents\gcreddy.xls")3) Set mySheet=myFile.worksheets("Sheet1")4) Rows_Count=mySheet.usedrange.rows.count5) For i= 1 to Rows_Count6) Agent=mySheet.cells(i,"A")7) pwd=mySheet.Cells(i,"B")8) 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"9) Dialog("Login").Activate10) Dialog("Login").WinEdit("Agent Name:").Set Agent11) Dialog("Login").WinEdit("Password:").SetSecure pwd12) Dialog("Login").WinEdit("Password:").Type micReturn13) Window("Flight Reservation").Close14) Next
4) Compare two excel files
Set objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objWorkbook1= objExcel.Workbooks.Open("E:\gcreddy1.xls")Set objWorkbook2= objExcel.Workbooks.Open("E:\gcreddy2.xls")Set objWorksheet1= objWorkbook1.Worksheets(1)Set objWorksheet2= objWorkbook2.Worksheets(1)For Each cell In objWorksheet1.UsedRangeIf cell.Value <> objWorksheet2.Range(cell.Address).Value Thenmsgbox "value is different"Elsemsgbox "value is same"End IfNextobjWorkbook1.closeobjWorkbook2.closeobjExcel.quitset objExcel=nothing
5) Data Driven Testing using Data Table methods
Datatable.AddSheet "gcreddy"Datatable.ImportSheet "C:\Documents andSettings\Administrator\Desktop\gcreddy.xls",1,3n=datatable.GetSheet (3).GetRowCountFor i= 1 to nDatatable.SetCurrentRow(i)
Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set datatable("agent",3)Dialog("Login").WinEdit("Password:").Set datatable("pwd",3)Dialog("Login").WinButton("OK").ClickWindow("Flight Reservation").CloseNext
Example 2):
Datatable.AddSheet "gcreddy"Datatable.ImportSheet "C:\Documents andSettings\Administrator\Desktop\gcreddy.xls",1,3n=datatable.GetSheet (3).GetRowCountFor i= 1 to nDatatable.SetCurrentRow(i)VbWindow("Form1").ActivateVbWindow("Form1").VbEdit("val1").Set datatable("V1",3)VbWindow("Form1").VbEdit("val2").Set datatable("V2",3)VbWindow("Form1").VbButton("ADD").Clickeres= Datatable.Value ("res",3)ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text")If eres=ares Thendatatable("res",3)=passelsedatatable("res",3)=failEnd IfNext
6) Open an Excel Spreadsheet
Set objExcel = CreateObject("Excel.Application")Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\gcreddy.xls")
7) Read an Excel Spreadsheet
Set objExcel = CreateObject("Excel.Application")Set objWorkbook = objExcel.Workbooks.Open _("C:\Scripts\New_users.xls")
intRow = 2
Do Until objExcel.Cells(intRow,1).Value = ""Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).ValueWscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value
Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).ValueWscript.Echo "LastName: " & objExcel.Cells(intRow, 4).ValueintRow = intRow + 1Loop
objExcel.Quit
8) Add Formatted Data to a Spreadsheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = TrueobjExcel.Workbooks.AddobjExcel.Cells(1, 1).Value = "Test value"objExcel.Cells(1, 1).Font.Bold = TRUEobjExcel.Cells(1, 1).Font.Size = 24objExcel.Cells(1, 1).Font.ColorIndex = 3
9) Sort an Excel Spreadsheet on Three Different Columns
Const xlAscending = 1Const xlDescending = 2Const xlYes = 1
Set objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objWorkbook = _objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls")
Set objWorksheet = objWorkbook.Worksheets(1)Set objRange = objWorksheet.UsedRange
Set objRange2 = objExcel.Range("A1")Set objRange3 = objExcel.Range("B1")Set objRange4 = objExcel.Range("C1")
objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _objRange4,xlDescending,xlYes
10) Short an excel sheet column
Set objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueSet objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objExcel.Cells(1, 1).Value = "5"objExcel.Cells(2, 1).Value = "1"objExcel.Cells(3, 1).Value = "0"objExcel.Cells(4, 1).Value = "3"
Set objRange=objworksheet.usedrangeobjrange.sort(objrange)
11) Add New Sheet to Excel File
Dim objExcelSet objExcel = createobject("Excel.Application")objExcel.Visible=TrueobjExcel.Workbooks.Addobjexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")
objExcel.Worksheets.AddobjExcel.ActiveWorkbook.SaveobjExcel.QuitSet objExcel=Nothing
12) Rename Sheets in an Excel File (WorkBook)
Dim objExcelSet objExcel = createobject("Excel.Application")objExcel.Visible=TrueobjExcel.Workbooks.Addobjexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")
objExcel.Worksheets("Sheet1").Name="gcr"objExcel.Worksheets("Sheet2").Name="qtp"objExcel.Worksheets("Sheet3").Name="training"
objExcel.ActiveWorkbook.SaveobjExcel.QuitSet objExcel=Nothing
13) Add a Sheet to an Excel File (WorkBook) and change the PositionDim objExcelSet objExcel = createobject("Excel.Application")objExcel.Visible=TrueSet myFile= objExcel.Workbooks.Add
objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")
objExcel.Worksheets.AddmyFile.Sheets("Sheet4").Move, myFile.Sheets(4)
objExcel.ActiveWorkbook.SaveobjExcel.QuitSet objExcel=Nothing
GUI Script:QTP Scripts examples1) Verify Login Boundary (Check all the boundary conditions of the Login dialog box. Checks to see if the correct message appears in the error window (Flight Reservation Message)
1) ApplicationDir = Environment("ProductDir")2) ApplicationPath = "\samples\flight\app\flight4a.exe"3) If Window("Flight Reservation").Exist(2) Then4) Window("Flight Reservation").Close5) SystemUtil.Run ApplicationDir & ApplicationPath6) Elseif Not Dialog("Login").Exist(1) Then7) SystemUtil.Run ApplicationDir & ApplicationPath8) End If9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value ("AgentName",dtGlobalSheet)10) Dialog("Login").WinEdit("Password:").Set Datatable.Value ("Password",dtGlobalSheet)11) Dialog("Login").WinButton("OK").Click12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and Datatable.Value ("Status",dtGlobalSheet)="Fail" Then13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").Check CheckPoint("Agent name must be at least 4 characters long.")14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value ("Status",dtGlobalSheet)="Pass" Then16) Reporter.ReportEvent PASS,"Login: ","Succeeded"17) Else18) Reporter.ReportEvent Fail,"Login: ","Combination #" & Datatable.GetCurrentRow & " was not according to Excel file"19) End If
2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.)
1) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"2) Dialog("Login").Activate3) Dialog("Login").WinButton("Cancel").Click4) If Dialog("Login").Exist (2) =True Then5) Reporter.ReportEvent 1,"sd","Fail"6) Else7) Reporter.ReportEvent 0,"sd","Pass"8) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"9) End If10) Dialog("Login").Activate11) Dialog("Login").WinEdit("Agent Name:").Set "asdf"12) Dialog("Login").WinButton("Cancel").Click13) If Dialog("Login").Exist (2) =True Then14) Reporter.ReportEvent 1,"sd","Fail"15) Else16) Reporter.ReportEvent 0,"sd","Pass"17) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"18) End If19) Dialog("Login").Activate20) Dialog("Login").WinEdit("Agent Name:").Set "asdf"21) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531"22) Dialog("Login").WinButton("Cancel").Click23) If Dialog("Login").Exist (2)=True Then24) Reporter.ReportEvent 1,"sd","Fail"25) Else26) Reporter.ReportEvent 0,"sd","Pass"27) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"28) End If29) Dialog("Login").Activate30) Dialog("Login").WinEdit("Agent Name:").Set "asdf"31) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531"32) Dialog("Login").WinButton("OK").Click
3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application.
1) Dim aRes,sRes,dRes,mRes2) VbWindow("VbWindow").Activate3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10"4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20"5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text")6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text")
7) VbWindow("VbWindow").VbButton("ADD").Click8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText9) VbWindow("VbWindow").VbButton("SUB").Click10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText11) VbWindow("VbWindow").VbButton("MUL").Click12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText13) VbWindow("VbWindow").VbButton("DIV").Click14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText15) v1=cdbl(v1)16) v2=cdbl(v2)17) aRes=cdbl (aRes)18) sRes=cdbl (sRes)19) mRes=cdbl (mRes)20) dRes=cdbl (dRes)21) If aRes=v1+v2 Then22) Reporter.ReportEvent 0,"Res","Addition Passed"23) else24) Reporter.ReportEvent 1,"Res","Addition Failed"25) End If26) If sRes=v1-v2 Then27) Reporter.ReportEvent 0,"Res","Subtraction Passed"28) else29) Reporter.ReportEvent 1,"Res","Subtraction Failed"30) End If31) If mRes=v1*v2 Then32) Reporter.ReportEvent 0,"Res","Multiplecation Passed"33) else34) Reporter.ReportEvent 1,"Res","Multiplecation Failed"35) End If36) If dRes=v1/v2 Then37) Reporter.ReportEvent 0,"Res","Division Passed"38) else39) Reporter.ReportEvent 1,"Res","Division Failed"40) End If
4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.)
1) Option explicit2) Dim bo,ao3) If Not window("Flight Reservation").Exist (2) Then4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"5) Dialog("Login").Activate6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8bce9984f1a15ea187a2da5b18c545abb01cf"
8) Dialog("Login").WinButton("OK").Click9) End If10) Window("Flight Reservation").Activate11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled")12) Window("Flight Reservation").WinButton("Button").Click13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled")17) If bo=False Then18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled"19) else20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled"21) End If22) If ao=True Then23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled"24) else25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled"26) End If
5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price)1) Option explicit2) Dim n,f,b,e3) If Not window("Flight Reservation").Exist (2) Then4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"5) Dialog("Login").Activate6) Dialog("Login").WinEdit("Agent Name:").Set "asdf"7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb"8) Dialog("Login").WinButton("OK").Click9) End If10) For n= 1 to 10 step 111) Window("Flight Reservation").Activate12) Window("Flight Reservation").WinButton("Button").Click13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
16) Window("Flight Reservation").WinRadioButton("First").Set17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText18) Window("Flight Reservation").WinRadioButton("Business").Set19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText20) Window("Flight Reservation").WinRadioButton("Economy").Set21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText22) f=cdbl(mid(f,2,len (f-1)))23) b=cdbl(mid(b,2,len (b-1)))24) e=cdbl(mid(e,2,len (e-1)))25) If f=3*e and b=2*e Then26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there"27) else28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there"29) End If30) Window("Flight Reservation").WinButton("Button_2").Click31) Window("Flight Reservation").Dialog("FlightReservations").WinButton("No").Click32) Next
6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price)
1) Option Explicit2) Dim t,p,tot,n3) For n= 1 to 10 step 14) If Not window("Flight Reservation").Exist (2) Then5) 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"6) Dialog("Login").Activate7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"8) Dialog("Login").WinEdit("Password:").SetSecure "4aa892d62c529f1c23298175ad78c58f43da8e34"9) Dialog("Login").WinButton("OK").Click10) End If11) Window("Flight Reservation").Activate12) Window("Flight Reservation").WinButton("Button").Click13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText19) t=cdbl (t)20) p=Cdbl(mid(p,2,len (p-1)))
21) tot=Cdbl(mid(tot,2,len (tot-1)))22) If tot=t*p Then23) Reporter.ReportEvent 0,"Res","Calculation Passed"24) else25) Reporter.ReportEvent 1,"Res","Calculation Failed"26) End If27) Next
7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.)
1) Option explicit2) Dim qtp,flight_app,f,t,i,j,x,y3) If Not Window("text:=Flight Reservation").Exist (7)= True Then4) QTP=Environment("ProductDir")5) Flight_app="\samples\flight\app\flight4a.exe"6) SystemUtil.Run QTP & Flight_app7) Dialog("text:=Login").Activate8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf"9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure "4aa5ed3daf680e7a759bee1c541939d3a54a5b65"10) Dialog("text:=Login").WinButton("text:=OK").Click11) End If12) Window("text:=Flight Reservation").Activate13) Window("text:=Flight Reservation").WinButton("window id:=6").Click14) Window("text:=Flight Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type "090910"15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetItemsCount16) For i= 0 to f-1 step 117) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").Select (i)18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetROProperty ("text")19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetItemsCount20) For j= 0 to t-1 step 121) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").Select (j)22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetROProperty ("text")23) If x <> y Then24) Reporter.ReportEvent 0,"Res","Test Passed"25) Else
26) Reporter.ReportEvent 1,"Res","Test Failed"27) End If28) Next29) Next
8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.)
1) If Not window("Flight Reservation").Exist (2) Then2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"3) Dialog("Login").Activate4) Dialog("Login").WinEdit("Agent Name:").Set "asdf"5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43"6) Dialog("Login").WinButton("OK").Click7) End If8) Window("Flight Reservation").Activate9) Window("Flight Reservation").WinButton("Button").Click10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a"12) ord=Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").GetVisibleText13) If ord= "a" Then14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data"15) else16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click18) End If
9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting)
1) Dim fso,myfile2) Set fso=createobject("scripting.filesystemobject")3) Set myfile= fso.opentextfile ("F:\gcr.txt",1)4) myfile.skipline5) While myfile.atendofline <> True6) x=myfile.readline7) s=split (x, ",")8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"9) Dialog("Login").Activate10) Dialog("Login").WinEdit("Agent Name:").Set s(0)
11) Dialog("Login").WinEdit("Password:").SetSecure s(1)12) Dialog("Login").WinButton("OK").Click13) Window("Flight Reservation").Close14) Wend
10) Count, how many Buttons and Edit boxes available in Flight Reservation main window.
1) If Not window("Flight Reservation").Exist (2) Then2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"3) Dialog("Login").Activate4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"5) Dialog("Login").WinEdit("Password:").Set "mercury"6) Dialog("Login").WinButton("OK").Click7) End If8) Set oDesc = Description.Create()9) oDesc("micclass").Value = "WinButton"10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc)11) Num_Buttons = Buttons.Count()12) Set oDesc1=Description.Create()13) oDesc1("micclass").Value="WinEdit"14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1)15) Num_Editboxes= editboxes.count ()16) sum= Num_Buttons+Num_Editboxes17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes
11) Verify search options in Open Order Dialog box
(After selecting open order, 3 search options should be enabled and not checked,After selecting Order No option, other options should be disabled,After selecting Customer Name, Flight date option enabled and Order No disabledAfter selecting Flight date option, Customer Name enabled and Order No disabled)
1) If Not window("Flight Reservation").Exist (2) Then2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"3) Dialog("Login").Activate4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c"6) Dialog("Login").WinButton("OK").Click
7) End If8) Window("Flight Reservation").Activate9) Window("Flight Reservation").WinButton("Button").Click10) Window("Flight Reservation").Dialog("Open Order").Activate11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")12) ce=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Enabled")14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked")15) cc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked")16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Checked")17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and fc="OFF") Then18) Reporter.ReportEvent 0,"Res","Pass"19) else20) Reporter.ReportEvent 1,"Res","Fail"21) End If22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"23) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked")24) If ono="ON" Then25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled")26) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")27) fd=false28) ono=false29) Reporter.ReportEvent 0,"Res","Pass"30) else31) Reporter.ReportEvent 1,"Res","Fail"32) End If33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "OFF"34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON"35) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked")36) If cn="ON" Then37) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled")
39) fd=True40) ono=false41) Reporter.ReportEvent 0,"Res","Pass"42) else43) Reporter.ReportEvent 1,"Res","Fail"44) End If45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "OFF"46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").Set "ON"47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Checked")48) If fd="ON" Then49) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")50) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")51) cn=True52) ono=false53) Reporter.ReportEvent 0,"Res","Pass"54) else55) Reporter.ReportEvent 1,"Res","Fail"56) End If
12) In Login Dialog box, Verify Help message (The message is ‘The password is 'MERCURY')
1) If Not Dialog("Login").Exist (2) Then2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"3) End If4) Dialog("Login").Activate5) Dialog("Login").WinButton("Help").Click6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password is 'MERCURY'").GetROProperty("text")7) If message="The password is 'MERCURY'" Then8) Reporter.ReportEvent 0,"Res","Correct message "&message9) else10) Reporter.ReportEvent 1,"Res","Worng message "11) End If
Web Scripts1) Count all opened Browsers on desktop and close them all?
Set oDesc = Description.Create()oDesc("micclass").Value = "Browser"Set Browsers =Desktop.ChildObjects (oDesc)
NumberofBrowsers = Browsers.Count()Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsersFor Counter=0 to NumberofBrowsers-1Browsers(Counter).CloseNext
2) Count, how many links available in Mercury Tours Home Page.
Set oDesc = Description.Create()oDesc("micclass").Value = "Link"Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc)NumberOfLinks = Lists.Count()Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks
3) Verify whether the 'Gmail' link available or not on Google Homepage
Option explicitDim oLink, Links, TotLinks, i, myLinkSet oLink = description.CreateoLink("micclass").value = "Link"SystemUtil.Run "D:\Program Files\Internet Explorer\IEXPLORE.EXE"set Links = Browser("name:=Google").page("title:=Google").ChildObjects(oLink)TotLinks = Links.countFor i =0 to TotLinks-1 myLink = Links(i).getroproperty("innertext")If mylink = "Gmail" Then reporter.ReportEvent 0,"res","Link Gmail available"End IfNext
4) Count number of Links, Edit Boxes available on Google Homepage?
Dim oLinkSet oLink=description.CreateSet oEdit=description.CreateoLink("micclass").value="Link"oEdit("micclass").value="WebEdit"Set Links=browser("name:=Google").page("title:=Google").ChildObjects(oLink)Set EditBoxes=browser("name:=Google").page("title:=Google").ChildObjects(
oEdit)TotLinks= Links.countTotEditBoxes=EditBoxes.countmsgbox TotLinksmsgbox TotEditBoxesReporter.ReportEvent 0,"Result","Total Links are: "&TotLinks&"Total edit Boxes are: "&TotEditBoxes
5) Count how many links available in a Web Page(any web page, using Regular Expressions)
Dim oLink,Links, TotLinksSet oLink=Description.CreateoLink("micclass").value="Link"Set Links=Browser("title:=.*").page("title:=.*").ChildObjects(oLink)TotLinks=Links.countmsgbox TotLinksReporter.ReportEvent 2,"Res","Total Links are: "&TotLinks
6) Verify Cost in jjperfumes.com 'Test Flow'i) Launch jjperfumes.com'ii) Select a product and enter some quantity'iii) select Add to Cart, capture Unit price, Quantity and Cost'iV) Remove $ symbols and compare'---------------------------------- -----
SystemUtil.Run "C:\Program Files\Internet Explorer\iexplore.exe","","C:\Documents and Settings\gcr.GCRC-9A12FBD3D9","open"Browser("Google").Page("Google").SyncBrowser("Google").Navigate "http://www.jjperfumes.com/"
Browser("Google").Page("JJ Perfumes-Discount perfume").Image("thumb_1845_WLINP50PSW").ClickBrowser("Google").Page("JJ Perfumes-Discount perfume_2").WebEdit("quantity").Set "4"Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebButton("Add To Cart").Click
Unit_Price = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]").GetROProperty("innertext")Qty = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebEdit("quantity[]").GetROProperty("value")Cost = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]_2").GetROProperty("innertext")
Qty=Cint(Qty)Unit_Price=Cdbl (Mid (Unit_Price,3))
Cost=Cdbl (Mid (Cost, 3))'Msgbox Unit_Price: Msgbox Qty: Msgbox Cost
If Cost=Qty * Unit_Price Then Reporter.ReportEvent micPass,"Res","Cost is Correct" Else Reporter.ReportEvent micFail,"Res","Cost is InCorrect"End If
Function To Create HTML Report
Dim StartTime,stTime, enTimeDim fso, ts,intCnt, intPass,intFailintPass=0intFail=0Const ForWriting = 2Function OpenFile (strFileName)StartTime = TimerstTime = TimeSet fso = CreateObject("Scripting.FileSystemObject")Set ts = fso.OpenTextFile(strFileName,2)'OpenFile = strFileURLCreateHeaderEnd Function*****************************Function To Close File
Dim objIE,strFileURLFunction CloseFile ( strFileURL,strEnv )Footer(strEnv)ts.close()Set objIE = CreateObject("InternetExplorer.Application")objIE.visible = TrueobjIE.Navigate strFileURLwait(5)
Set objIE=nothingEnd Function***********************Function to Clear Cookies()
Function ClearCookies()SystemUtil.Run "iexplore.exe"WebUtil.DeleteCookiesSet objBrowser=Description.CreateobjBrowser("micclass").value="Browser"Set objBCount = Desktop.ChildObjects(objBrowser)
intBrowserCount = objBCount.CountstrHwnd=Browser("creationtime:=" & intBrowserCount).GetROProperty("hwnd")SystemUtil.CloseProcessByHwnd(strHwnd)End Function
***********************
Function to send Email
Function SendMail()
If k=0 Then'NothingElsemsgsub = " Geo_PostalCode pattern searchTest Results:" &vbcrLf &"One or more of the Test Cases Failed." &vbcrLf &"See attachment for details."End IfSet objConf = CreateObject("CDO.Configuration")cdoSendUsingPort=2sMailServerName="smtp.phx.move.com"cdoAnonymous=cdoNONEobjConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPortobjConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = sMailServerNameobjConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoAnonymous 'cdoBasicobjConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = FalseobjConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "corp\ NRaoJ "'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "123K!r45"objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60objConf.fields.UpdateSet objMsg = CreateObject("CDO.Message")objMsg.Configuration = objConf
objMsg.to = "[email protected]"objMsg.From = "[email protected]"objMsg.Subject = "~Geo_PostalCode pattern search"objMsg.TextBody =msgsubdoc=strFilepathobjMsg.AddAttachment(doc)
objMsg.SendSet objMsg = NothingNewMail = TrueEnd Function
***********************Function to create append excel
Function LogFile
Set objExcel=CreateObject("Excel.Application")objExcel.visible=FalseobjExcel.workbooks.open(strFilePath)r=1Do Until len(objExcel.cells(r,1))=0r=r+1Loop
objExcel.cells(r,1).value="Step Name"objExcel.cells(r,2).value="Step Description"objExcel.cells(r,3).value="Test Results"objExcel.DisplayAlerts = FalseobjExcel.SaveobjExcel.QuitSet objExcel = NothingEnd Function
***********************
Function to get the Application Environment on which the script is running
Function GetEnv()
Set fso=Createobject("Scripting.FileSystemObject")sFile="C:\WINDOWS\system32\drivers\etc\hosts"Set MyFile=fso.OpenTextFile(sFile,1, True)DosEnv=MyFile.ReadLineIf instr(sEnv,"PRODUCTION")>0 ThenGetEnv="Production"Exit doElseif instr(sEnv,"Staging")>0 ThenGetEnv="Staging"Exit doElseif instr(sEnv,"QA MAINTENANCE")>0 ThenGetEnv="QAM"Exit do
Elseif instr(sEnv,"qap.")>0 ThenGetEnv="qap"Exit doEnd IfLoop While MyFile.AtEndOfStream=FalseEnd Function
***********************
Function To Create HTML Report
Dim StartTime,stTime, enTime
Dim fso, ts,intCnt, intPass,intFailintPass=0intFail=0Const ForWriting = 2Function OpenFile (strFileName)StartTime = TimerstTime = TimeSet fso = CreateObject("Scripting.FileSystemObject")Set ts = fso.OpenTextFile(strFileName,2)'OpenFile = strFileURLCreateHeaderEnd Function
Web Scripts-IIWeb Application Testing using QTP.Web forms verification, Object state verification, Database Testing and Links verification.
1) Script to get the list of links in Google and do spell check =====================================Dim d set mw=CreateObject("Word.Application") set d=Description.Create d("micclass").value="Link" set a=Browser("Google").page("Google").childobjects(d) for i=0 to a.count-1 mw.WordBasic.filenew s=a(i).getROProperty("innertext") mw.WordBasic.insert s if mw.ActiveDocument.Spellingerrors.count>0 then Reporter.ReportEvent 1,"Spelling","spelling error :"&s end if
mw.ActiveDocument.Close(False) next mw.quit set mw=nothing
2) Script to check ON the checkboxes in yahoo mail inbox ========================================
Dim dSet d=Description.Created("micclass").value="WebCheckBox"Set c=Browser("Inbox (17) - Yahoo! Mail").Page("Inbox (17) - Yahoo! Mail").ChildObjects(d)For i=1 to 10c(i).set "ON"Next
3) script to select a mail having subject 'hi' or 'HI' =================================n=Browser("yahoo").Page("yahoo").WebTable("Inbox").RowCount For i=2 to n s=Browser("yahoo").Page("yahoo").WebTable("Inbox").GetCellData(i,7) If lcase(trim(s))="hi" Then Browser("yahoo").Page("yahoo").WebCheckBox("index:="&i-1).set "ON" End If Next4) 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 Ifm.Send otl.Quit Set m = Nothing Set otl = NothingEnd Function
Call SendMail("[email protected]","hi","This is test mail for tsting","")Adv VBScripts
5) Open Internet Explorer and navigate to yahoo mail ===================================Dim ieSet ie=CreateObject("InternetExplorer.Application")ie.Visible=Trueie.Navigate "www.yahoomail.com"x=Browser("CreationTime:=0").GetROProperty("title")msgbox x
6) Function for Counting Objects from any opened web page
Function Objects_Count(myObject) Dim Objects Set Objects=Description.Create Objects("micclass").value=myObject Set Object=Browser("title:=.*").Page("title:=.*").ChildObjects(Objects) TotObjects=Object.Count Msgbox TotObjectsEnd FunctionCall Objects_Count("WebButton")
7) Create script for links validation and set results into an excel file
Set objDesc=Description.Create
objDesc("micclass").value="Link"
Set objColl=Browser("title:=.*").page("title:=.*").ChildObjects(objDesc)
msgbox objColl.count
Set objExcel=Createobject("Excel.application")
objExcel.Visible=True
objExcel.Workbooks.Add
set objSheet=objExcel.ActiveSheet
objSheet.cells(1,1)="LinkName"
set c1=objSheet.cells(1,1)
c1.font.color=vbBlue
objSheet.cells(1,2)="TargetUrl"
Set c2=objSheet.cells(1,2)
c2.font.color=vbBlue
objSheet.cells(1,3)="ActualUrl"
Set c3=objSheet.cells(1,3)
c3.font.color=vbBlue
objSheet.cells(1,4)="Status"
Set c4=objSheet.cells(1,4)
c4.font.color=vbBlue
For i=0 to objColl.count-37 step 1
strName=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRoProperty("name")
TargetUrl=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRoProperty("url")
msgbox TargetUrl
Browser("title:=.*").page("title:=.*").Link("index:="&i).click
wait(4)
ActualUrl=Browser("title:=.*").GetRoProperty("url")
msgbox ActualUrl
If instr (1,TargetUrl,ActualUrl,1) > 0 Then
Reporter.ReportEvent micPass,"Link Name "&strName,"Link Validation done"
objSheet.cells(i+2,1)=strName
objsheet.cells(i+2,2)=TargetUrl
objsheet.cells(i+2,3)=ActualUrl
objsheet.cells(i+2,4)="Link Validation done"
Set c5= objsheet.cells(i+2,4)
c5.font.color=vbGreen
Else
Reporter.ReportEvent micFail,"Link Name "&strName,"Link validation fail"
objSheet.cells(i+2,1)=strName
objsheet.cells(i+2,2)=TargetUrl
objsheet.cells(i+2,3)=ActualUrl
objsheet.cells(i+2,4)="Link Validation fail"
Set c5= objsheet.cells(i+2,4)
c5.font.color=vbRed
End If
Browser("title:=.*").Back
Next
Set objWbook=objExcel.ActiveWorkbook
objWbook.SaveAs "E:\gcreddy.xls"
objExcel.Quit
Set objExcel=nothing
qtp real-time script exampleQuickTest Professional is an Industry leading and famous Testing Tool for Functional & Regression Testing QTP uses VB Script for scriptingWe can use QTP Tool features as well as VB Script Flow Control statements for inserting verification points.If we want to use VB Script Flow Control statements for inserting flow control statements, then we need to define Test results.QTP has provided a facility to define Test Results, using ‘Reporter’ Utility Object to define test results.Using Comments is a best practice in QTP Scripting to understand the code.Creating functions for modular code is a best practice and intelligent task in scripting /Programming.using Automation Objects is an useful task in QTP scriptingusing Built-in functions and regular expressions is an useful task.
QTP Scripting has several types:
a) GUI scripting: using scripting for GUI based Applicationsb) Web scripting: Automation web based applications using vb scriptc) Database scripting: Using scripting for Database operations such as data comparisons and validations.d) Excel scripting: Handling and using Excel files in Test Automation
Excel Scripting Examples-2
1) Data Driven Testing for Login Operation by fetching from an excel file
Dim objExcel, myFile, mySheetSet objExcel=CreateObject("Excel.Application")Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls")Set mySheet=myFile.Worksheets("Sheet1")Rows_Count=mySheet.usedrange.rows.count
For i= 2 to Rows_Count step 1SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A")
Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B")Wait (2)Dialog("text:=Login").WinButton("text:=OK").ClickWindow("text:=Flight Reservation").CloseNext
myFile.CloseobjExcel.QuitSet objExcel=Nothing-----------------------------------------2) Data Driven Testing for Login Operation by fetching Test Data from anexcel file and Export Result to the Same file
Dim objExcel, myFile, mySheetSet objExcel=CreateObject("Excel.Application")Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls")Set mySheet=myFile.Worksheets("Sheet1")Rows_Count=mySheet.usedrange.rows.count
For i= 2 to Rows_Count step 1SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A")Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B")Wait (2)Dialog("text:=Login").WinButton("text:=OK").Click
If Window("text:=Flight Reservation").Exist(12) ThenWindow("text:=Flight Reservation").CloseResult="Login Operation Sucessful"mySheet.Cells(i,"C")=ResultElseSystemUtil.CloseDescendentProcessesResult="Login Operation Failed"mySheet.Cells(i,"C")=ResultEnd IfNextmyFile.SavemyFile.CloseobjExcel.QuitSet objExcel=Nothing------------------------------
3) 'Data Driven Testing for Login Operation by fetching Test Data from anexcel file' Export Result and Error message to the Same file'Dim objExcel, myFile, mySheetSet objExcel=CreateObject("Excel.Application")Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls")Set mySheet=myFile.Worksheets("Sheet1")Rows_Count=mySheet.usedrange.rows.count
For i= 2 to Rows_Count step 1SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A")Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B")Wait (2)Dialog("text:=Login").WinButton("text:=OK").Click
If Window("text:=Flight Reservation").Exist(12) ThenWindow("text:=Flight Reservation").CloseResult="Login Operation Sucessful"mySheet.Cells(i,"C")=ResultElse
Error_Message = Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").GetROProperty("text")SystemUtil.CloseDescendentProcessesResult="Login Operation Failed"mySheet.Cells(i,"C")=ResultmySheet.Cells(i,"D")=Error_MessageEnd IfNextmyFile.SavemyFile.CloseobjExcel.QuitSet objExcel=Nothing
------------------------------------------------------------------4) 'Open 1 to 10 Orders in Flight Reservation window and capture Order Numbers and Customer Names
'Export to an Excel FileDim objExcel,myFile,mySheet,iSet objExcel = CreateObject("Excel.Application")
Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls")Set mySheet = myFile.Worksheets("Sheet2")row=1mySheet.Cells(row,"A")="OrderNo"mySheet.Cells(row,"B")="CustomerName"
If Not Window("Flight Reservation").Exist(3) ThenSystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set "asdf"Dialog("Login").WinEdit("Password:").SetSecure "4d0a254623fcf8d10630f10b6ca8e776fcbc0717"Dialog("Login").WinButton("OK").ClickEnd IfFor i = 1 to 10 Step 1 Window("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set iWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").ClickCustomer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text")row=row+1mySheet.Cells(row,"A") = imySheet.Cells(row,"B") = Customer_NameNextmyFile.SavemyFile.CloseobjExcel.QuitSet objExcel =Nothing
System Administration1) Getting Local Computer Information
Set objComputer = CreateObject("Shell.LocalMachine")
Wscript.Echo "Computer name: " & objComputer.MachineNameWscript.Echo "Shutdown allowed: " & objComputer.IsShutdownAllowedWscript.Echo "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabledWscript.Echo "Guest access mode: " & objComputer.IsGuestAccessModeWscript.Echo "Guest account enabled: " & _ objComputer.IsGuestEnabled(0)Wscript.Echo "Multiple users enabled: " & _ objComputer.IsMultipleUsersEnabled
Wscript.Echo "Offline files enabled: " & _ objComputer.IsOfflineFilesEnabledWscript.Echo "Remote connections enabled: " & _ objComputer.IsRemoteConnectionsEnabledWscript.Echo "Undock enabled: " & objComputer.IsUndockEnabled
2) Restart a Computer
strComputer = "atl-dc-01"Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate,(Shutdown)}!\\" & _ strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems objOperatingSystem.Reboot()Next
3) Shut Down a Computer
strComputer = "."Set objWMIService = GetObject_ ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & _ strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem") For Each objOperatingSystem in colOperatingSystems objOperatingSystem.Win32Shutdown(1)Next 4) Modify System Startup Delay
strComputer = "."Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colStartupCommands = objWMIService.ExecQuery _ ("Select * from Win32_ComputerSystem")
For Each objStartupCommand in colStartupCommands objStartupCommand.SystemStartupDelay = 10 objStartupCommand.Put_Next
MS Word Scripts
1) create a word document and write some data
====================dim mwset mw=CreateObject("Word.Application")mw.Documents.Addmw.selection.typetext "hello"mw.ActiveDocument.SaveAs "e:\gcreddy.doc"mw.quitset mw=nothing
2) Create word, Create table and write all the services names ========================================Set mw = CreateObject("Word.Application")mw.Visible = TrueSet dc = mw.Documents.Add()Set objRange = dc.Range()dc.Tables.AddobjRange,1,3Set objTable = dc.Tables(1)x=1strComputer = "."Set wms=GetObject("winmgmts:\\" & strComputer & "\root\cimv2")Set colItems = wms.ExecQuery("Select * from Win32_Service")For Each s in colItemsIf x > 1 ThenobjTable.Rows.Add()End IfobjTable.Cell(x, 1).Range.Font.Bold = TrueobjTable.Cell(x, 1).Range.Text = s.NameobjTable.Cell(x, 2).Range.text = s.DisplayNameobjTable.Cell(x, 3).Range.text = s.Statex = x + 1Next
3) script to display all the doc files in all the drives in the system=========================================Dim mwSet mw=CreateObject("Word.Application")Set fs=createobject("Scripting.FileSystemObject")Set d=fs.Drivesmw.FileSearch.FileName="*.doc"For each dr in d
msgbox drmw.FileSearch.LookIn=drmw.FileSearch.SearchSubFolders=Truemw.FileSearch.ExecuteFor each i in mw.FileSearch.FoundFilesprint iSet f=fs.GetFile(i)print f.Name&" "&f.Size&" "&f.DateCreatedprint "-------------------------------------------------------------------"NextNextmw.Quit
4) Counting the number of times a word appears in a word document=========================================
Set objWord=CreateObject("Word.Application")Set myfile=objWord.Documents.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\xyz.doc")strText="gcreddy"strRead=myfile.ContentSet RegExp=new regexpregexp.ignorecase=Trueregexp.global=Trueregexp.pattern=strTextSet matches=regexp.execute(strRead)matchesFound=matches.countmsgbox matchesfoundmyfile.closeset objFso=Nothing
XML ScriptsVBScript to read XML
Set xmlDoc = CreateObject(“Msxml2.DOMDocument”)xmlDoc.load(“D:\gcreddy.xml”)Set ElemList = xmlDoc.getElementsByTagName(“segment”)filepath = ElemList.item(0).getAttribute(“filePath”)MsgBox filepath
Set ElemList = xmlDoc.getElementsByTagName(“description”)plot = ElemList.item(0).TextMsgBox plot
How Get Root Element attribute’s value from XML fileFunction GetRootElementAttributeValueFromXML(sFileNameWithPath,sAttribute) ‘ Why we need to ADD 2 because each attribute followed by (=) and (“) iLenOfValue=len(sAttribute) + 2 Set doc = XMLUtil.CreateXML() doc.LoadFile sFileNameWithPath Set root = doc.GetRootElement()IF instr(1,root,sAttribute) <= 0 then Reporter.ReportEvent micFail,sAttribute,”Not Found in XML file.” exitrun(0) Else sStartPos=instr(1,root,sAttribute) + iLenOfValue sEndPos=instr(sStartPos,root,”"”") GetRootElementAttributeValueFromXML=mid(root,sStartPos,sEndPos – sStartPos)End ifEnd Function msgbox(GetRootElementAttributeValueFromXML(“c:\temp\gcreddy.xml”,”MerchantId”))
QTP Skills7 Steps to Improve Skills in QTP
I) QTP Testing Process
In order to use QTP IDE properly, you should have good command on QTP Testing process.a) Planninga) Analyzing the AUTb) Implementing Automation Frameworkc) Creating/Selecting Test casesd) Collecting Test Datae) Automation Infrastrucure developmentf) Tool settings Configuration & Globalization
b) Generating the basic Test
1) Keyword driven methodology/Shared object repository method/Preparing the script manually
2) Descriptive programming/Programmatic Descriptionsi) Entering Programmatic Descriptions Directly into Statementsii) Using Description Objects for Programmatic Descriptionsiii) Retrieving Child Objectsiv) Using the Index Property in Programmatic Descriptions
c) Enhancing the Test
a) Adding Commentsb) Creating Checkpoints Programmaticallyc) Synchronizationd) Parameterizatione) Inserting Programmatic statementsf) Enhancing Tests with the windows APIg) Calling Functions and/or Actions
d) Debugging the Test
e) Running the Test
f) Analyzing the Test Results
g) Reporting Defects
a. Manual Defect Reportingb. Tool based Defect Reportingc. Integration with Quality Center
II) VB Script
VbScript is the QTP Tool Default Scripting Language for applaying Progamming Logic, so learn Vbscript indepth.
Below fundamentals & Features are Important:
a) VBScript Fundamentals
1)Introductiona) Scripting Languages vs. Programming Languagesb) Basic Features of VBScriptc) Hosting Environments & Script Enginesd) Crating & running a Script
2) Variables and Constantsa) VBScript data typesb) Declaring Variables and Option Explicit Statementc) Assigning Values to Variables
d) Scalar Variables and Array Variablese) Dynamic Arrays, Dimensional Arraysf) Constantsg) Variables Vs. Constants
3) VBScript Operatorsa) Operator Precedenceb) Arithmetic Operatorsc) Comparison Operatorsd) Concatenation Operatorse) Logical Operators
4) Flow Control (I. Conditional Statements)a) VBScript Conditional Statementsb) Running a state if condition is true (Single line Syntax)c) Running a block of Statements if Condition is trued) Running Certain Statements if a Condition is True and Running Others if a Condition is Falsee) Deciding Among Several Alternatives (IF..Else If…)f) Executing a certain block of statements when two / more conditions are True (Nested If...)g) Deciding Among Several Alternatives (Selct case Statement)
5) Flow Control (II. Looping through the code)a) Do...Loop (Loops while or until a condition is True.)b) While...Wend (Loops while a condition is True.)c) For...Next: Uses a counter to run statements a specified number of times.d) For Each...Next (Repeats a group of statements for each item in a collection or each element of an array.)e) Nested Loops
6) VBScript Proceduresa) Sub Proceduresb) Function Proceduresc) Creating & Calling Procedures
7) Coding Conventionsa) Constant Naming Conventionsb) Variable Naming Conventionsc) Variable Scope Prefixesd) Object Naming Conventionse) Code Commenting Conventions
b) Advanced VBScript
1) VBScript Intrinsic (Pre-Defined) Functionsa) Conversions
b) Dates/Timesc) Formatting Stringsd) Input/Outpute) Mathf) Miscellaneousg) Roundingh) Stringsi) Variants
2) Regular Expressionsa) Uses for Regular Expressionsb) Regular Expression Syntaxc) Build a Regular Expressiond) Order of Precedencee) Ordinary Charactersf) Character Matchingg) Anchorsh) Alternation and Groupingi) Backreferencesj) Regular Expression (RegExp) Object
3) File System Operations
a) Computer File Systemb) Working with Drives and Foldersc) Working with Flat Filesd) Working with Word Docse) Working with Excel Sheets
4) Database Operations
a) ActiveX Data Objectsb) ADODB Connection Object & Recordset Objectc) Test Database Creation & Collecting Test Datad) Databases Connections (Ms-Access, SQL Server and Oracle)e) Data Driven Testing by fetching Data from a Databasef) Data Comparisons
5) Methods, Objects and Classes
a) VBScript Global Methodsb) QTP Methodsc) FileSystemObjectd) Dictionary Objecte) Classes
6) Error Handling
a) Error Handling Guidelinesb) Error Handling in QuickTest Professionalc) Error Preventingd) Synchronizatione) QTP Exit Statementsf) VBScript error handling vs. Recovery Scenariosg) On Error Statementh) Err Object
III) Automation Framework
Automation Framework is a Systamatic Approach for Automating, SoftwareTesting Process.In order to Create & Run Tests as well oraganizing & Managing Automation Resources, a well defined Framework required.
Framework may vary from one company to another.
Below concepts are important to learn:o Test Automation Frameworko Types of Frameworko Keyword Driven Frameworko Framework Structureo Developing a Robust Automation Frameworko Implementing & Managing Automation Resources
IV) COM/DCOM Technologies
When working with QTP, It is important to know, Microsoft Applications like:
o MS Excel,o Ms Word,o Outlook Express ando Internet Explorer
V) XML
XML is an extremely popular and useful format. It can be used in several areas in QTP.Ex:o Exporting objects,o Environment Variables,o Data driven Testingo Data transporting etc.
VI) SQL
SQL Knowledge is highly recomendable in order to perform Database Testing using QTPBelow concepts are important:o Database Fundamentalso Data Creation & Exportingo Database Connectionso Select Statements
VII) HTML, DOMIn order to work with Web based Applications, It is important to femiliar with web technologies like:o HTML, DHTMLo Flasho HTTP like Protocolso DOM (Documentation Object Model)
Error Handling in QTP
Error Handling:Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.
Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions.
Error Handling in QuickTest Professional:QTP and VBScript give the Test Engineer some tools to handle errors and Exceptions.
Error Preventing:
A good method for using error handling is to try to prevent them.
When an error occurred, Report it in detail. When working with GUI objects, use the Window.Exist property. Every If…Then..End If statement has the Else part, the same forSelect Case. Use Case Else.
Error Handling Methods in QTP and VB Script:
a) Synchronizationb) Exist Propertyc) Recover Scenarios
d) On Error Statement
Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops.
Whenever possible, you use structured exception handling in your code, rather than resorting to unstructured exception handling and the On Error statement.
Parts:
GoToline
Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.
GoTo 0
Disables enabled error handler in the current procedure and resets it to Nothing.
GoTo -1
Disables enabled exception in the current procedure and resets it to Nothing.
Resume Next
Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects.
on Error Resume Next
Example1:Dim aa = 1
b-2MsgBox a + b ' displays result without showing error
Example2:
Function Sum(Num1, Num2)If IsNumeric(Num1) = False Or IsNumeric(Num2) = False ThenOn Error Resume NextErr.Raise vbObjectError + 100, "Sum Function", _"One or more parameters are invalid."Exit FunctionEnd IfSum = Num1 +Num2
End Function Call Sum("gcreddy","QTP") 'Comes out without showing errorCall Sum(100,200) ' returns sum of 100,200 as 300
e) Error Object
The Err object is an intrinsic object with global scope — there is no need to create an instance of it in your code.
The properties of the Err object are set by the generator of an error — Visual Basic, an Automation object, or the VBScript programmer. The default property of the Err object is Number.
Err.Number contains an integer and can be used by an Automation object to return an SCODE.
When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err. Example:
On Error Resume NextErr.Raise 6 ' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)Err.Clear ' Clear the error.
Err Object Properties and Methods
Properties
Description Property HelpContext Property HelpFile Property Number Property Source Property
Methods
Clear Method
Raise Method
f) Exit Statement
Open 30 to 40 Orders in Flight Reservation Window, if some records not available handle the situation
Option ExplicitDim Order_NumberIf Not Window("Flight Reservation").Exist(3) ThenSystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"Dialog("Login").ActivateDialog("Login").WinEdit("Agent Name:").Set "gcreddy"Dialog("Login").WinEdit("Password:").SetSecure "4c2e1e65bf29943393b6940f116d35231ce5fb7e"Dialog("Login").WinButton("OK").ClickEnd If
For Order_Number= 30 to 40 step 1Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_NumberWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist(3) ThenWindow("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").ClickWindow("Flight Reservation").Dialog("Open Order").WinButton("Cancel").ClickReporter.ReportEvent micWarning,"Res", "Up to "& Order_Number-1 &" Order only available"Exit ForEnd IfNext
VB Script for QTP
It explains VB Script in QTP orientation, It covers all most all VB Script Fundamentals and Features.It describes, Variables, constants declarations, usage of operators, VB Script flow control statements, Procedures, Coding conventions, Regular Expressions, File system Operations, Database Operations etc..
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 Language2) Interpreter converts high level instructions into machine language line by line3) It doesn’t create executable file.4) No need to compile the program5) 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 Design10) 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 program4) It takes numerous lines of code5) It increases development time7) It Increases maintenance of cost8) Explicit support of Data Types9) Rich support for User Interface Design10) Rich Support for Graphics Design
Example Programming Languages are:
COBOL, Basic, C, C++, VC++, VB Etc...
VB Script Fundamentals And FeaturesVB 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 Variables
Definition 1):Variable is a named memory location for storing program informationDefinition 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,ax=100y=100a=x=yMsgbox a 'It returns True
b) Holding Program Result
Example:Cost=Tickets*Price
c) Passing parameters
d) To store data that returned by functionsExample:myDate=Now ‘ It returns current data & time
e) To hold dataExample: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 cityDim xWe 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 notgenerally 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 'RightDim 9ab 'WrongDim ab9 'Right
b) Cannot contain an embedded period.Dim abc 'RightDim ab.c 'worngDim ab-c 'wrongDim ab c 'wrongDim 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,zx=10y=20z=x+ymsgbox z 'Returns 30Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90End FunctionCall 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 = 200City = “Hyderabad”
X=100: Y=200Scalar 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 zero-based, 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) = 256A(1) = 324A(2) = 100 A(3) = 55
Similarly, the data can be retrieved from any element using an index into the particulararray 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 secondnumber 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 Operators
Operators are used for performing mathematical, comparison and logical operations.VB Script has a full range of operators, including arithmetic operators, comparisonoperators, concatenation operators, and logical operators.
Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.
Arithmetic and logical operators are evaluated in the following order of precedence.
1) Arithmetic Operators:
Operator Description1) 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,ca=10b=3c=a^bmsgbox c '1000
c=a*bmsgbox c '30
c=a/bmsgbox c '3.33333333
c=a\bmsgbox c '3
c=a mod bmsgbox c '1
c=a-b
msgbox c '7
Dim a,b,ca=10b=2c=3d=c*a^b'c=a+bmsgbox d '1000
Addition (+) operator
Dim a,b,ca=10b=2c=a+bmsgbox c '12 (if both are numeric, then it adds)
a="10"b=2c=a+bmsgbox c '12 (one is string another numeric, then it adds)
a="10"b="2"c=a+bmsgbox c '102 (if both are strings, then it concatenates)
a="hydera"b="bad"c=a+bmsgbox c 'hyderabad
a="gagan"b=2c=a+bmsgbox c 'error
Concatenation Operator
Dim a,b,ca=10b=2
c=a&bmsgbox c '102
a="10"b=2c=a&bmsgbox c '102
a="10"b="2"c=a&bmsgbox c '102
a="hydera"b="bad"c=a&bmsgbox c '102
2) Comparison Operators
Used to compare expressions.
Operator Description1) = (Equal to) Used to compare expressions.2) <> (Not equal to) Used to compare expressions.3) < Less than 4) > Grater than5) <= Less than or equal to 6) >= Greater than or equal to7) Is Object equivalence
Example:
Dim x,y,zx=10y=20z=x=yMsgbox z 'False
x=10y=20z=x>yMsgbox z 'False
x=10
y=20z=x>=yMsgbox z 'False
x=10y=20z=x<>yMsgbox z 'True
x=10y=20z=x<yMsgbox z 'True
x=10y=20z=x<=yMsgbox z 'True3) Concatenation Operators
Operator Description1) Addition Operator (+)
Sums two numbersIf Then1) 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 Syntax1) Not Performs logical negation on an expression result= Not expression2) And Performs a logical conjunction on two expressions. result= expression1 And expression23) Or Performs a logical disjunction on two expressions. result= expression1 Or expression24) 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 InputInput = 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, andreturns a value indicating which button the user clicked.
Example:Dim MyVarMyVar = MsgBox ("Hello World!", 65, "MsgBox Example")MyVar contains either 1 or 2, depending on which button is clicked.
Conditional Statements
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 myDatemyDate = #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 xx= 20If x>10 Then
msgbox "x value is: "&xmsgbox "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 xx= Inputbox (" Enter a value")If x>100 ThenMsgbox "Hello G.C.Reddy"Msgbox "X is a Big Number"Msgbox "X value is: "&XElse Msgbox "GCR"Msgbox "X is a Small Number"Msgbox "X value is: "&XEnd 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 xx= Inputbox (" Enter a value")
If x>0 and x<=100 ThenMsgbox "Hello G.C.Reddy"Msgbox "X is a Small Number"Msgbox "X value is "&x
Else IF x>100 and x<=500 ThenMsgbox "Hello GCR"Msgbox "X is a Medium Number"
Else IF x>500 and x<=1000 ThenMsgbox "Hello Chandra Mohan Reddy"Msgbox "X is a Large Number"
Else Msgbox "Hello Sir"Msgbox "X is a Grand Number"End IfEnd IfEnd If
5) Executing a certain block of statements when two / more conditions are True (Nested If...)
Example:
Dim State, RegionState=Inputbox ("Enter a State")Region=Inputbox ("Enter a Region")
If state= "AP" ThenIf Region= "Telangana" Thenmsgbox "Hello G.C.Reddy"msgbox "Dist count is 10"
Else if Region= "Rayalasema" Thenmsgbox "Hello GCR"msgbox "Dist count is 4"
Else If Region= "Costal" Then
msgbox "Hello Chandra mohan Reddy"msgbox "Dist count is 9"
End IfEnd IfEnd IfEnd 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-yMsgbox "Hello G.C.Reddy"Msgbox "Substraction of x,y values is "&Result
Case "mul"Result= x*yMsgbox "Hello G.C.Reddy"Msgbox "Multiplication of x,y values is "&Result
Case "div"Result= x/yMsgbox "Hello G.C.Reddy"Msgbox "Division of x,y values is "&Result
Case "mod"Result= x mod yMsgbox "Hello G.C.Reddy"Msgbox "Mod of x,y values is "&Result
Case "expo"Result= x^yMsgbox "Hello G.C.Reddy"Msgbox"Exponentation of x,y values is "&Result
Case ElseMsgbox "Hello G.C.Reddy"msgbox "Wrong Operation"
End Select
Looping Through Code
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 conditionStatements----------- -----------Loop Or, we can use this below syntax:
Example:
Dim x
Do While x<5 x=x+1Msgbox "Hello G.C.Reddy"Msgbox "Hello QTP"Loop
ii) Do Statements----------- -----------Loop While condition
Example:
Dim xx=1Do Msgbox "Hello G.C.Reddy"Msgbox "Hello QTP"x=x+1Loop While x<5
b) Repeating a Statement Until a Condition Becomes True
iii) Do Until conditionStatements----------- -----------Loop Or, we can use this below syntax:Example:
Dim xDo Until x=5 x=x+1Msgbox "G.C.Reddy"Msgbox "Hello QTP"Loop
Or, we can use this below syntax:
iv) Do Statements----------- -----------Loop Until conditionOr, we can use this below syntax:
Example:
Dim xx=1Do Msgbox “Hello G.C.Reddy” Msgbox "Hello QTP"x=x+1Loop Until x=5
2 While...Wend Statement
Executes a series of statements as long as a given condition is True.
Syntax:While conditionStatements----------- ----------- Wend
Example:
Dim xx=0 While x<5 x=x+1msgbox "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 xFor x= 1 to 5 step 1Msgbox "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
StatementsNext
Example: (1
Dim a,b,x (3)a=20b=30x(0)= "Addition is "& a+b x(1)="Substraction is " & a-bx(2)= "Multiplication is " & a*bx(3)= "Division is " & a/b
For Each element In xmsgbox elementNext
Example: (2
MyArray = Array("one","two","three","four","five")For Each element In MyArraymsgbox elementNext
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
OrSub 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 FunctionOrFunction Procedure name (argument1, argument2)Statements----------------------End Function
Example: 1
Function Celsius(fDegrees)Celsius = (fDegrees - 32) * 5 / 9End 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 ourprocedure. 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)-Or-MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."
To call a Sub procedure from another procedure, type the name of the procedurealong 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 elseLogin="Login Operation Unsucessful" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click 'Msgbox LoginEnd IfEnd Function
'***************************************' Closing Application'***************************************Function Close_App()if Window("Flight Reservation").Exist(3) ThenWindow("Flight Reservation").CloseEnd IfEnd Function
'***************************************' Open Order'***************************************Function Open_Order(ord) ordnum=0 On Error Resume NextWindow("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Button").ClickWindow("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ordWindow("Flight Reservation").Dialog("Open Order").WinButton("OK").Clickordnum=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 elseOpen_Order= "Order Number "&ordnum&" Not Opened/ Not Available"Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").ClickWindow("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click 'Msgbox Open_OrderEnd IfEnd Function
'******************************************' Update Order'******************************************Function Update_Order(Tickets)Window("Flight Reservation").ActivateWindow("Flight Reservation").WinEdit("Tickets:").Set TicketsWindow("Flight Reservation").WinButton("Update Order").Clickwait(10)update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text")If update="Update Done..." ThenUpdate_Order= "Order Updated Sucussfully"'Msgbox Update_OrderElseWindow("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").ClickUpdate_Order= "Order Not Updated"'Msgbox Update_OrderEnd IfEnd 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("[email protected]","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 yourVBScript statements violates one or more of the grammatical rules of theVBScript 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
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 FunctionReturns the absolute value of a number.
Dim numnum=abs(-50.33)msgbox num
2) Array FunctionReturns a variant containing an Array
Dim AA=Array("hyderabad","chennai","mumbai")msgbox A(0)ReDim A(5)A(4)="nellore"msgbox A(4)
3) Asc FunctionReturns the ANSI character code corresponding to the first letter in a string.
Dim numnum=Asc("A")msgbox num* It returns the value 65 *
4) Chr FunctionReturns the character associated with the specified ANSI character code.
Dim charChar=Chr(65)msgbox char
* It returns A *
5) CInt FunctionReturns an expression that has been converted to a Variant of subtype Integer.
Dim numnum=123.45myInt=CInt(num)msgbox MyInt
6) Date FunctionReturns the Current System Date.
Dim mydatemydate=Datemsgbox mydate
7) Day FunctionEx1) Dim mydaymyday=Day("17,December,2009")msgbox myday
Ex2) Dim mydaymydate=datemyday=Day(Mydate)msgbox myday
8) DateDiff FunctionReturns 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 FunctionReturns a whole number between 0 and 23, inclusive, representing the hour of the day.
Dim mytime, Myhourmytime=Nowmyhour=hour (mytime)msgbox myhour
10) Join FunctionReturns 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 FunctionReturns a Variant of subtype Date indicating the current system time.
Dim mytimemytime=Timemsgbox mytime
13) VarType Function
Returns a value indicating the subtype of a variable.
Dim x,yx=100y=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.56y=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,yVal="Hyderabad"x=Left(Val,3)Msgbox x 'Hyd
Val=100x=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 FunctionDim AnyString, MyStrAnyString = "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 FunctionReturns the number of characters in a string or the number of bytes required to store a variable.
Ex 1):Dim Mystringmystring=Len("G.C.Reddy")msgbox mystring
Ex 2):Dim MystringMystring=Inputbox("Enter a Value")Mystring=Len(Mystring)Msgbox Mystring
16) Mid FunctionReturns a specified number of characters from a string.
Dim Val, x,yVal="Hyderabad"x=Mid(Val,3,4)Msgbox x 'dera
Val=100x=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 FunctionReturns the number of seconds that have elapsed since 12:00 AM (midnight).
Function myTime(N)Dim StartTime, EndTimeStartTime = TimerFor I = 1 To NNextEndTime = TimermyTime= EndTime - StartTimemsgbox myTimeEnd FunctionCall myTime(2000)
17) isNumeric Function
Dim MyVar, MyCheckMyVar = 53MyCheck = IsNumeric(MyVar)
msgbox MyCheckMyVar = "459.95"MyCheck = IsNumeric(MyVar)msgbox MyCheckMyVar = "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 InputInput = 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 MyVarMyVar = 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 numnum=172.499num=Round(num)msgbox num
22) StrReverseIt returns reverse value of the given sringx=strreverse ("dabaraedyh")msgbox x
23) strCompIt compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd)Dim x, yx="cd": y="bcd"
comp=strcomp(x,y)msgbox comp
24) ReplaceIt replace a sub string with given value (another sub string)mystring=Replace("kb script", "k","v")msgbox mystring
User Defined Functions----------------------------------------------------------i) Launching ApplicationNavigation:
a) Launch the Browser
b) Enter / Select the URL (“www.jjperfumes.com”)
Verification: Capture the Browser Name and Verify
—————
Function Launch_App()
SystemUtil.Run “C:\Program Files\Internet Explorer\IEXPLORE.EXE”,”",”C:\Documents
and Settings\Administrator”,”open”
Browser(“Google”).Page(“Google”).Sync
Browser(“Google”).Navigate “http://www.jjperfumes.com/”
Wait (8)
Browser_Name = Browser(“Google”).GetROProperty(“title”)
If Browser_Name=”JJ Perfumes-Discount perfume cheap brand name perfumes,
fragrance & cologne online” Then
Launch_App=”Jjperumes.com Browser Launched Sucessfully”
Msgbox Launch_App
Else
Launch_App=”Jjperumes.com Browser Not Launched”
Msgbox Launch_App
End If
End Function
——————————————————————————————–ii) Customer RegistrationPre-Setup: Launching Application
Navigation:
a) Select Registration Link in jjperfumes.com homepage
b) Enter all Mandatory details
c) Select Submit button
Verify: Capture confirmation Message and Verify
Function Register(Email)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume”).Link(“Register”).Click
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebList(“usertype”).Select “Retailer”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“firstname”).Set “dfgdg”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“lastname”).Set “dgdfgdfg”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebList(“gender”).Select “Male”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“address1″).Set “dfgfdgf”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“phone”).Set “9222222223″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“email”).Set Email
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“city”).Set “chennai”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebList(“state”).Select “MS – MISSISSIPPI”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“zip”).Set “23456″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“password”).SetSecure
“3c30bbc7daa0dccb83c2941bb87fa0709d34″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“conPass”).SetSecure
“3c30bbcdb1f7a32d27a56f70a60f7d1e4159″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebButton(“Submit”).Click
Wait (5)
Confirm_Message = Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-
Discount perfume_3″).WebElement(“Registered
successfully.”).GetROProperty(“innertext”)
If Confirm_Message=”Registered successfully. “Then
Register=”Customer Registration Sucessful”
Msgbox Register
Else
Register=”Registration Failed”
Msgbox Register
End If
End Function
——————-
Function Register(Email)
Set myBrowser=Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-
Discount perfume_2″)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume”).Link(“Register”).Click
myBrowser.WebList(“usertype”).Select “Retailer”
myBrowser.WebEdit(“firstname”).Set “dfgdg”
myBrowser.WebEdit(“lastname”).Set “dgdfgdfg”
myBrowser.WebList(“gender”).Select “Male”
myBrowser.WebEdit(“address1″).Set “dfgfdgf”
myBrowser.WebEdit(“phone”).Set “9222222223″
myBrowser.WebEdit(“email”).Set Email
myBrowser.WebEdit(“city”).Set “chennai”
myBrowser.WebList(“state”).Select “MS – MISSISSIPPI”
myBrowser.WebEdit(“zip”).Set “23456″
myBrowser.WebEdit(“password”).SetSecure
“3c30bbc7daa0dccb83c2941bb87fa0709d34″
myBrowser.WebEdit(“conPass”).SetSecure
“3c30bbcdb1f7a32d27a56f70a60f7d1e4159″
myBrowser.WebButton(“Submit”).Click
Wait (5)
Confirm_Message = Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-
Discount perfume_3″).WebElement(“Registered
successfully.”).GetROProperty(“innertext”)
If Confirm_Message=”Registered successfully. “Then
Register=”Customer Registration Sucessful”
Msgbox Register
Else
Register=”Registration Failed”
Msgbox Register
End If
End Functioniii) Login OperationPre-Requisites:
a) Launching Application
b) Customer Registration
Navigation:
a) Select “Login” Link in jjperfumes.com homepage
b) Enter Email and Password
c) Select “Login Button”
Verify: Check existence of LogOut Link
—————–
Function Login(Email, Pwd)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume”).Link(“Login”).Click
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“username”).Set Email
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebEdit(“password”).Set Pwd
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_2″).WebButton(“Login”).Click
If Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount
perfume_3″).Link(“Logout”).Exist(10) Then
Login=”Login Operation Sucessful”
Msgbox Login
Else
Login=”Login Failed”
Msgbox Login
End If
End Functioniv) Closing Application————————
Navigation:
————
a) Check the Existence of jjperfumes.com Browser
b) Close the Browser window (If exists)
—————–
Function Launch_App()
SystemUtil.Run “C:\Program Files\Internet Explorer\IEXPLORE.EXE”,”",”C:\Documents
andSettings\Administrator”,”open”
Browser(“Google”).Page(“Google”).Sync
Browser(“Google”).Navigate “http://www.jjperfumes.com/”
Wait (8)
Browser_Name = Browser(“Google”).GetROProperty(“title”)
If Browser_Name=”JJ Perfumes-Discount perfume cheap brand name perfumes,
fragrance & cologne online” Then
Launch_App=”Jjperumes.com Browser Launched Sucessfully”
Msgbox Launch_App
Else
Launch_App=”Jjperumes.com Browser Not Launched”
Msgbox Launch_App
End If
End Function
**********************************************************v) Login Operation In Flight Reservation Application
Function Login (Agent, Password)
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 Agent
Dialog(“Login”).WinEdit(“Password:”).Set Password
wait 2
Dialog(“Login”).WinButton(“OK”).Click
If Window(“Flight Reservation”).Exist(12) Then
Window(“Flight Reservation”).Close
Login=”Login Operation Sucessful”
Msgbox Login
Else
SystemUtil.CloseDescendentProcesses
‘If Dialog(“Login”).Dialog(“Flight Reservations”).Exist(2) Then
‘Dialog(“Login”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
‘Dialog(“Login”).WinButton(“Cancel”).Click
‘End if
Login=”Login Failed”
Msgbox Login
End if
End Function
———————————vi) Open Order In Flight Reservation ApplicationFunction Open_Order(Order_Number)
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
Order_Number
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrdNum = Window(“Flight Reservation”).WinEdit(“Order No:”).GetVisibleText()
OrdNum=CInt(OrdNum)
If OrdNum=Order_Number Then
Open_Order= Order_Number& ” Opened sucessfully”
Msgbox Open_Order
Else
Open_Order= Order_Number& ” Not Opened”
Msgbox Open_Order
End If
End Function
——————————————vii) Update Order In Flight Reservation ApplicationFunction Update_Order(Tickets)
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 “2″
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Window(“Flight Reservation”).WinEdit(“Tickets:”).Set Tickets
Window(“Flight Reservation”).WinButton(“Update Order”).Click
Wait (10)
Message = Window(“Flight Reservation”).ActiveX(“Threed Panel
Control”).GetROProperty(“text”)
If Message=”Update Done…” Then
Update_Order=”Order Updated Sucessfully”
Msgbox Update_Order
Else
Update_Order=”Order Not Updated”
Msgbox Update_Order
End If
End Function
—————————————–viii) ‘Write Function to Count how many Browsers opened on desktop and close them allFunction Close_Browsers()
Dim oBrowser, Browsers, TotBrowsers, i
Set oBrowser=Description.Create
oBrowser(“micclass”).Value=”Browser”
Set Browsers=Desktop.ChildObjects(oBrowser)
TotBrowsers=Browsers.Count
Msgbox TotBrowsers
For i= 0 to TotBrowsers-1 Step 1
Browsers(i).close
Next
End Function
—————————ix) ‘Write Function to Count how many Buttons available in FR WindowFunction Count_Buttons()
Dim oButton, Buttons, TotButtons, i
Set oButton=Description.Create
oButton(“Class Name”).Value=”WinButton”
Set Buttons=Window(“text:=Flight Reservation”).ChildObjects(oButton)
TotButtons=Buttons.Count
Msgbox TotButtons
End Function
Call Count_Buttons()
—————————–x) ‘Write Function to Count how many Objects available in FR Window by specified Test Object classFunction Count_Objects(Object)
Dim obj, Objects, TotObjects, i
Set obj=Description.Create
obj(“Class Name”).Value=Object
Set Objects=Window(“text:=Flight Reservation”).ChildObjects(obj)
TotObjects=Objects.Count
Msgbox TotObjects
End Function
Call Count_Objects(“WinRadioButton”)
Call Count_Objects(“WinButton”)
Call Count_Objects(“WinEdit”)
Call Count_Objects(“WinComboBox”)
——————————–xi) ‘Write function to capture all button names one by one from Login Dialog BoxFunction Capture_Buttons()
Dim oButton, Buttons, TotButtons, i, myButton
Set oButton=Description.Create
oButton(“Class Name”).Value=”WinButton”
Set Buttons=Dialog(“text:=Login”).ChildObjects(oButton)
TotButtons=Buttons.Count
For i= 0 to TotButtons-1
myButton=Buttons(i).GetRoProperty(“text”)
Msgbox myButton
Next
End Function
Call Capture_Buttons()
——————————————
xii) ‘Write function to Count Howmany Links available in Google HomepageFunction Count_Links()
Dim oLink, Links, TotLinks, i
Set oLink=Description.Create
oLink(“micclass”).Value=”Link”
Set Links=Browser(“title:=Google”).Page(“title:=Google”).ChildObjects(oLink)
TotLinks=Links.Count
Msgbox TotLinks
End Function
Call Count_Links()
——————————————————————————-
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 objFsoSet 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 citiesSet 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 PropertySets and returns the comparison mode for comparing string keys in a Dictionary object.
Key Property
Sets a key in a Dictionary object.
Item PropertySets or returns an item for a specified key in a Dictionary object. For collections, returnsan item based on the specified key. Read/write. Examples:
a to Elements 1) AddDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline"objDictionary.Add "Printer 3", "Printing"
2) Delete All a Elements fromDictionary
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 strKeyNext
objDictionary.RemoveAllcolKeys = objDictionary.Keys
Wscript.Echo VbCrLf & "Second run: "For Each strKey in colKeys Wscript.Echo strKeyNext
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 strKeyNext
objDictionary.Remove("Printer 2")colKeys = objDictionary.Keys
Wscript.Echo VbCrLf & "Second run: "For Each strKey in colKeys Wscript.Echo strKeyNext
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
VB Script General Examples1) Write a program for finding out whether the given year is a leap year or not?
Dim xyearxyear=inputbox ("Enter Year")If xyear mod 4=0 Thenmsgbox "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 Oddnumber?
Dim numnum=inputbox ("Enter a number")
If num mod 2=0 Thenmsgbox "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, sumnum1=inputbox ("Enter num1")num2=inputbox ("Enter num2")sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion requiremsgbox ("Sum is " &sum)
4) Read P,T,R values and Calculate the Simple Interest?
Dim p,t, r, sip=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 interestmsgbox ("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, sumnum=inputbox ("Enter a Four digit number")If Len(num) = 4 Thensum=0sum=sum+num mod 10num=num/10num= left (num, 3)sum=sum+num mod 10num=num/10num= left (num, 2)sum=sum+num mod 10num=num/10num= left (num, 1)sum=sum+num mod 10msgbox ("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,revnum= inputbox("Enter a number")If len(num)=4 Thenrev=rev*10 + num mod 10num=num/10num= left(num,3)rev=rev*10 + num mod 10num=num/10num= left(num,2)rev=rev*10 + num mod 10num=num/10num= left(num,1)rev=rev*10 + num mod 10msgbox "Reverse Order of the number is "&rev Elsemsgbox "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 Distinctionb) If average marks Greater than or equal to 60 and less than 75 , then grade is Firstc) If average marks Greater than or equal to 50 and less than 60 , then grade is Secondd) If average marks Greater than or equal to 40 and less than 50 , then grade is Thirde) Minimum marks 35 for any subject, otherwise 'no grade fail')
Dim e,m,p,c, tote=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 totIf cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Thenmsgbox "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 Thenmsgbox "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 Thenmsgbox "Grade is Third"else msgbox "No Grade, Fail"End IfEnd If End IfEnd If
8) Display Odd numbers up to n?
Dim num,nn=Inputbox ("Enter a Vaule")For num= 1 to n step 2 msgbox numNext
9) Display Even numbers up to n?
Dim num,nn=Inputbox ("Enter a Vaule")For num= 2 to n step 2msgbox num Next
10) display natural numbers up to n and write in a text file?
Dim num, n, fso, myfilen= inputbox ("Enter any Value")num=1For num= 1 to n step 1Set fso= createobject ("scripting.filesystemobject")set myfile=fso.opentextfile ("E:\gcreddy.txt", 8, true)myfile.writeline nummyfile.closeNext
11) Display Natural numbers in reverse order up to n?
Dim num,nn=Inputbox ("Enter a Vaule")For num=n to 1 step -1msgbox numNext
12) Display Natural numbers sum up to n? (Using For...Next Loop)
Dim num, n, sumn= inputbox ("Enter a Value")sum=0For num= 1 to n step 1sum= sum+numNextmsgbox sum
13) Display Natural numbers sum up to n? (using While...Wend Loop)
Dim num, n, sumn= inputbox ("Enter a Value")While num <=cdbl (n)sum= sum+numnum=num+1Wendmsgbox sum
14) Display Natural numbers sum up to n? (Using Do...Until...Loop)
Dim num, n, sumn= inputbox ("Enter a Value")sum=0num=1Do sum= sum+numnum=num+1Loop Until num =cdbl (n+1)msgbox sum
15) Write a Function for Natural Numbers sum up to n?
Function NNumCou (n)
Dim num, sumsum=0For num= 1 to n step 1sum= sum+numNextmsgbox sumEnd Function
16) Verify weather the entered 10 digit value is a numeric value or not?
Dim a,x,y,z,numnum=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"elseMsgbox "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,numnum=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" Thenmsgbox "It is a Numeric Value"End IfEnd If
If len (num) <> 10 ThenMsgbox "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 years-10%, 5 years -11%)Dim amount, duration, intramount=inputbox("enter amount")If amount<10000 Thenmsgbox "low amount"elseFor duration=1 to 5 If duration=1 Thenintr=amount*7/100msgbox "1 year intrest is: " &intr
else if duration=2 Thenintr=amount*8/100msgbox "2 years intrest is: " &intr
else if duration=3 Thenintr=amount*9/100msgbox "3 years intrest is: "&intr
else if duration=4 Thenintr=amount*10/100msgbox "4 years intrest is: "&intr
else if duration=5 Thenintr=amount*11/100
msgbox "5 years intrest is: "&intrelsemsgbox "invalid data"End IfEnd IfEnd IfEnd IfEnd IfNextEnd 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_Startval=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_Startval=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 IfElse 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_AscIf 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,iDim strlen, counter,valsinglecounter=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 IfNext
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