text:
This action might not be possible to undo. Are you sure you want to continue?
I) Basic features of QTP
o QTP Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007. o o o o QTP is an Object Based Testing Tool. QTP is for functional and Regression Testing. It follows Keyword driven approach. It supports Windows Operating Environment only.
o It supports GUI based (Graphical user interface) and Web based Applications Automation, does not support CUI (Command user interface) Applications. o It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages with respect to license.) o It has adapted Microsoft Visual Basic Scripting edition for programming and excel like spread sheet for Data driven testing. o SQL (Structured query language) embedded or inserted with QTP, so we can use SQL statements directly from QTP. o It can be integrated with other Tools like WinRunner and Quality Center.
o It 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. o It was derived from Astra QuickTest (mother tool of QTP).
o It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers like Mozilla and AOL, opera Etc apart from IE. o o QTP is a Desktop Application (I-Tier/Stand alone). QTP has two types of License, 1. Seat or Node locked License, 2. Concurrent or float license. Seat license for one system and Concurrent License, we can use for any system but one user at any time. If we want multiple concurrent licenses we can purchase. o QTP has UNI code support.
Version History of QTP
• • • • • • • • • • Astra Quick test (Mother tool of QTP) 1.0 to 5.0 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
Add-In Manager
QTP supports almost all industry leading technologies, but by default it does not support, with respect to add in license it supports. Default Add- ins of QTP are: • • • Activex Visual basic Web.
Other available Add Ins are: .NET, Java, People soft, Siebel, TE (Terminal Emulators), SAP for GUI, Sap for Web, Oracle Apps, Web Services etc. During QTP launching it shows Add in manger dialog box, Add in Manger lists out all available Add Ins in the company. User needs to select appropriate Add Ins for his application or AUT. One can select more than one Add Ins also; if we select unnecessary Add Ins QTP performance will be reduced.
Launching QTP We can launch QTP BY selecting desktop icon otherwise start > programs> QTP Professional > QTP. During launching it shows Add-In Manager. Quick Test Launches 4 . Add-in manager window Select appropriate Add Ins and click okay.
II) Key Elements of QTP Tool Window 5 .
It is a global concept. statement etc). used for creating. Expert view.Test in VB script format.QTP Tool Window 1) Test Pane: It is programming interface of QTP. viewing and deleting test scripts. Test: It is a set of statements or set of one or more actions. method. (It is a local concept) Action: It is a set of Statements. editing. Test pane has 2 views. (Keyword such as function. QTP Test Pane-Expert View 6 . Statements may have keywords. (It is a local concept) Statement: A minimal executable unit.
Note 2: Technical users use expert view and business user use key word view. Note 3: User can customize Test pane view options.Test in Icon based GUI format. if you perform any modifications in one view those automatically reflects in another view. QTP Test Pane-Keyword View Note1: Here in test pane Test is same but views are different. 7 . Navigation: Tools Menu> view options> we can use font size and colors etc.Key word view.
Active Screen 8 . It can be used for understanding and editing the test easily. apply and okay. it takes snap shots of every statement that user performed action or operation on AUT. Navigation: View menu>active screen (for launching and closing) Configuring active screen: view>options>active screen tab>increase /Decrease capture level.2) Active Screen It has an optional element of QTP. Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP.
used for Data driven testing. Sql Server. Global Sheet. etc) and Data bases (MS access. 1. 2. excel sheets. Enter test data directly into Data Table and use.Data Table 9 . 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. oracle. Data table available in 2 ways: 1. Run time data table. 2. QTP has Data table methods for performing operations on data table.for entire test /used for all actions in the test. QTP Tool window. (Available in result window) Run time is a carbon copy of design time data table.for specific action only. Action Sheets.3) Data Table It has an integrated spread sheet (Excel like). etc.) It has two types of sheets. Design time data table. Importing data from external files (Flat files. (Attached with every test) 2. 1.
It can be used for debugging the tests by step-by-step execution. We use step into. Navigation: View menu>debug viewer (for launching and closing) QTP Tool Window-Debug Viewer 10 . step over and step out commands for debugging.4) Debug Viewer It is used for locating and rectifying or fixing errors. (debug commands) Through Debug viewer user can watch variables and change values of variables temporarily.
Navigation: View menu >missing resources (for launching and closing) 6) Information This pane shows syntax errors automatically during saving the test.5) Missing Resources It can be used for showing missing resources those attached to current test such as (recovery scenarios. library files etc). Navigation: view menu> information 11 .
open existing tests. deleting and splitting actions. Tool Bar options 3. 1. synchronizing points. information. Insert Menu: Through this menu user can inserting check points. Data Table. View menu: Through this menu we can launch and close. export tests in zip format. out put values. Menu options 2. Edit Menu: It provides editing options and renaming. save tests. Debug viewer. Short cut keys (for Some important operations only) File menu: Through file menu user can create. 12 . missing resources etc. active screen.QTP Tool Window-Information Pane 7) QTP Commands QTP Commands are available in 3 ways.
Through this menu we can create /modify/delete objects information and we can associate repositories. Debug Menu: This menu provides debug commands for step by step execution. Through this menu we can create. analog recording and Low level recording. In this menu object spy option available. Automation Menu: This menu provides Record.(Properties and values) In this menu Virtual object option available. Through this menu we can contact technical support people and we can send feedback. view options and object identification configuration.In this menu step generator available. Through this menu we can set tool options as well as test pane view options. 13 . using this user can generate recordable and non-recordable scripts. Run options and Run setting options Through this menu we can start normal recording. through this option we can create virtual objects. Tools Menu: This menu provides Tools settings option. Through insert menu user can create new actions. through this we can get object's information. Window Menu: This menu provides QTP tool window style settings. call existing actions and copy existing actions. Resources Menu: This menu provides object repository and recovery scenarios options. Through insert menu user can insert VB Script conditional and loop statements and transaction points (Start and End). Through this menu we can check for updates and download or install directly. Help Menu: This menu provides QTP help as well as VB Script help. Through this menu we can insert/remove/break points. modify and delete recovery scenarios. running and also we run tests. Through this menu we can stop recoding.
III) QTP Testing Process Planning o o o o o Analyzing the AUT Generating/Selecting Test cases for Automation Collecting Test Data Automation Framework Implementation QTP Tool Settings Configuration Generating Tests o o o Recording Keyword driven methodology Descriptive Programming Enhancing Tests o o o o o o o o o o o Inserting Checkpoints Inserting Output values Adding Comments Synchronization Parameterization Inserting Flow Control Statements Calling Functions/Actions Generating Steps though Step Generator Inserting Transaction Points Using Regular Expressions Using Environment Variables Debugging Tests o o o o Debug Commands & Break Points Step by step execution Watching Variables Changing values of variables Running Tests o Normal Execution 14 .
modular actions helps make our tests easier to read. try to keep the amount of steps we plan to include in each action to a minimum. Then determine the functionality that we want to test.o o o o Batch Execution AOM Scripting Tests Running through framework Scheduled Execution Analyzing Results o o o o QTP Result window Defining our own Results Exporting Results Deleting Results Reporting Defects o o o Manual Defect Reporting Tool based Defect Reporting Working with Quality Center Analyzing the AUT Before we begin creating a test. so that we can load the required QuickTest add-ins.NET. which will be represented by our test's actions. consider the various activities that customers perform in our application to accomplish specific tasks. Which objects and operations are relevant for the set of business processes that need to be tested? Which operations require customized keywords to provide additional functionality? While we are thinking about the business processes we want to test. or . To do this. First. Java. such as Web. 15 . Creating small. and maintain. follow. As we plan. we need to analyze our application and determine our testing needs. Each action should emulate an activity that a customer might perform when using your application. determine the development environments in which our application controls were developed. consider how we can divide these processes into smaller units.
Recording and Running: In QTP there are 3 recording modes available for preparing Tests. We can use this mode for recording continuous mouse operations. Normal Recording It records User Mouse and Keyboard operations on AUT with respect to objects. It shows Record and Run Settings. 6. Navigation: 1. graphs. Navigation: Automation>Record Or Select Record option on automation toolbar Or Use short cut key (F3) Steps for preparing a Test (through Recording): 1. Click OK Perform actions on AUT Stop recording. Select type of Environment (Windows or Web) 4. Save the Test 2. If we select Second option. it asks for the path of the AUT. 8. During recording QTP generates VbScript statements in Test Pane. 7. After Providing the path it records only on that particular application. Keep tool under recording mode 2. Automation >Analog Recording (OR) Use Short cut Key (Shift + ALT+F3) Steps for preparing a TEST (through Analog Recording): 16 . 1. The Track file is not editable. generates total user actions in a Track File. Put AUT in base state 2. Simultaneously it stores objects information into object repository. Record and Run only on If we select first option it records on any opened application on Desktop.) 5. It is not useful for recording normal operations why because it does not generate steps for each operation. Record and Run Test on any open window based applications 2. Analog Recording: It records the exact mouse and keyboard operations. Select Record Option 3. paints etc. Select Record Option (It shows two Options : 1. but unable to record continuous mouse operations like Digital Signatures.
after showing the Window it records with respect to that window co-ordinates. Keep tool under recording mode 2. It records User actions 7. we have to show the window (AUT). Record relative to the following window If we select first option QTP records User operations with respect to Desktop coordinates. Low Level Recording It records some operations on Non-supported environments apart from Normal operations. 1. Navigation: 1. Record relative to the screen 2. Stop Recording 3. If we select Second option.) 5. 6. 2. Select any one option in the dialog box and click Start Analog record. 3. This mode records at the object level and records all run time objects as window or winobject Test objects. Automation >Low Level Recording Steps for preparing a TEST (through Low Level Recording): 1) Launch AUT (or we can launch AUT through QTP) 2) Select Record option 3) Automation> Low Level Recording 4) Perform options on AUT 5) Stop Recording 6) Save the Test 17 . 4. Launch AUT (or we can launch AUT through QTP) Select Record option Automation>Analog Recording Analog Recording Settings Dialog box opens (In this Dialog box two options available.1. Use Low Level Recording for recording in an environment not recognized by QTP.
edit boxes. links. check boxes etc. dictionary object class. Reporter for defining results.Object Repository Object Repository: It is a storage place of QTP where we can store the objects information 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. Ex: Creating objects in file system object class. excel. those can be used for performing specific operations. SystemUtil for launching/closing the application. Ex: WinEdit. Application class etc.MTR extension) 2. adodb. WinButton. etc… Note: Test objects names vary from one environment to Ex: Run time Test objects in Test objects in VB objects windows Environment Environment buttons WinButton VBButton Edit box WinEdit VBEdit Check box Wincheckbox Vbcheckbox another. Link.. WebPages. Test objects 3. Test objects in web Environment WebButton WebEdit Webcheckbox Utility objects They are QTP reserved objects used for testing and result reporting. Utility objects 4.connection class. 2. as software objects. Local repository (. Software objects: We call windows.TSR extension) 18 . Run time objects: The objects present in the AUT. Ex: Buttons. 1. etc… Test Objects: References of Run time objects. Run time objects 2. WebButton. Environment for using environment variables Automation objects/User defined objects User can create objects. Services for inserting transaction points 4. Ex: 1. buttons. Types of Object in QTP: There are four types of object available in QTP. Automation objects/User defined objects. 3. There are two types of repository available in QTP. which has structure and properties. 1. Shared repository(.
That can be shared among number of tests. User can add some more objects to Local repository User can perform rename.Local Repository Shared Repository: User (Test Engineer) creates shared repository by adding objects. 19 . delete operations in local repository.Local Repository: QTP creates a Local Repository for every action automatically during Recording. As it is QTP internal file user no need to save modifications. That cannot be shared among tests. Using this method user can perform modifications on objects easily. Navigation: Resource menu>object repository (Short cut key Ctrl+R) QTP.
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.>close repository b. if we select second option it stores all default objects.) Renaming objects a. >close repository b. if we select fourth option. we have to select object classes then it stores that class objects. Deleting objects a. we can select more than one class also.Operations on Object Repository Adding objects a. Local Repository: Navigation: open local repository (resource menu>object repository) >objects>Add objects to Local>show the object>click ok (No need to save separately. it saves automatically) B. Shared Repository: Navigation: Resource menu>object repository manager>object>Add objects>show the window/object>click ok o Selected object only o Default object types o All objects types o Selected object types (If we select first option it stores Selected objects only. Local Repository: Resources > object repository >select object and right click >choose delete option >confirm deletion>. 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. if we select third option it stores All objects including static objects. Local Repository: Resources > object repository >select object and right click >choose rename option >modify the name>release the mouse. Associating objects repositories to an action Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok 20 .
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. Navigation: View>Locate in repository >show the object>click Ok>it locates specified object in the repository. In Repository manager) View Options Locate in Repository This feature can be used for identifying objects from application to repository. if we do not want source files we can delete. Highlight in Application This feature can be used for identifying objects from repository to application. In local repository 3. (Test objects names. Importing Repository from XML file We can import XML file to our repository. Defining new test objects Navigation: Object>Define new test object >Select Environment>Select Class of the object>Enter name of the object>Click Add>click close>Select object >select property name>enter value (like this select one by one properties and enter values)>save Note: This feature can be used for preparing tests before the AUT is ready. Navigation: File >export Test objects to XML Enter the file name and Save with xml extension. Navigation: Select object in the repository >view>highlight in application>it highlights specified objects in the application.(1. Spying objects For getting objects information. source repository files will be available. 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. Exporting Repository to an XML file We can export our repository file to an xml file. In tools Menu 2. it can be available in 3 Areas. using this we can get objects information. property & Values) QTP is providing a feature called Object Spy. 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 21 .
attached text . text.Descriptive Programming Entering / Providing objects information directly into the test script is called Descriptive Programming. Set. then we can provide more properties information by separating with commas. OK . In this method of script creation. Static Programming 2.Winedit("attached text:=Agent Name:"). Click . Dynamic Programming Static Programming In this style of script generation.Winedit("attached text:=Password:"). Activate. WinEdit and WinButton – Test Objects 2.Set "asdf" dialog("text:=Login"). 22 . Agent Name:.Click Note: 1.Methods Note2: If we feel one property information is not sufficient for recognizing the object uniquely.Property names 3.exe" dialog("text:=Login").Activate dialog("text:=Login"). Password:. Login."width:=60"). Dialog.Property values or Logical Names of the Object 4. we provide objects information directly into the script. 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. 1. Ex: Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a. Setsecure. we no need to have Object Repositories.Set "mercury" dialog("text:=Login").Winbutton("text:=OK". Descriptive programming is basically 2 types.
in local repository and in repository manager.Winedit(Agent). then we can handle modifications easily. ------------------------------------------------------------------If we want maintain 'Objects information' in centralized location then we can use Constants. Ok="text:=OK" Note: we can declare no of Constants in a line by separating with Camas (. ------------------------------------------------------------------- 23 .Set "mercury" Dialog(Login). we can use object spy feature. Agent="attached text:=Agent Name:" Const Pwd ="attached text:=Password:". properties and values). Creating a Library file Place Constants in Notepad and save as .).Click Advantages: If we maintain Object Information in the centralized location.Set "asdf" Dialog(Login).Note 3: If we want to get objects information (Test objects.exe" Dialog(Login).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. Steps: Creating Constants: Const Login="text:=Login". This feature is available in Tools Menu.Winedit(Pwd"). if we take other line then we have to use Const Statement again.Activate Dialog(Login).Winbutton(Ok).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. we can load the library file during run-time Syntax: ExecuteFile "Path of the Library file(.
Click Note1: Create Description objects and put into one library file.value=204 oAgent("attached text").value="Login" oLogin("width").Winbutton(oOK).Activate Dialog(oLogin).value="OK" Generating Tests using Properties collection Objects Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.value=320 oLogin("height").Set "mercury" Dialog(oLogin).Create oAgent=description.Create Entering Properties Information into Objects oLogin("text").exe" Dialog(oLogin).Winedit(oPassword). we can generate tests.Winedit(oAgent). provide properties information and use description objects in the test script. we can maintain Objects information in the Centralized location by putting collection objects in a Library file.value="Agent Name:" oPassword("attached text"). by associating that library file. Creating Properties Collection Objects Set Set Set Set oLogin=description.Create oOk=description.Set "asdf" Dialog(oLogin).value="Password:" oOk("text"). Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy.Dynamic Programming In this style of script generation. first we create description objects. ---------------------------------------------------- 24 . ---------------------------------------------------In this style of script creation also.Create oPassword=description.
Syntax: Object hierarchy.WinEdit("Agent Name").click Close Method: It closes the window.Close Browser("Browser").Activate Window("Flight Reservation").select "item" Ex: A.Winbutton("ok"). Close Ex: Window("Flight Reservation"). Syntax: Object hierarchy.WinRadioButton("Business"). For setting the value of an edit box Syntax: Object Hierarchy.Select "London" 25 .Set "asdf" b. a.WinCheckBox("Order No.Set c. Click Ex: Dialog("Login").Close DBL CLICK: It Double clicks the object. Activate Ex: Dialog("Login").").Dialog box.WinComboBox("Fly From:"). Set Ex: Window("Flight Reservation").Set "ON/off" Ex: Window ("Flight Reservation"). Dialog("Open Order"). SET "Value" Ex: Dialog ("Login").Set "ON" Select Method: It is used for selecting an item from a combo box or list box. Window("Flight Reservation").Methods or Operations Activate: It activates dialog boxes/Windows Syntax: Object hierarchy. Browser window etc.Activate Click Method: It clicks on an object (Buttons) Syntax: Object hierarchy. Set Method: It can be used in three ways. Selecting/Deselecting check boxes Syntax:object Hierarchy. Selecting a Radio Button Syntax: Object Hierarchy.
getitemscount Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").Navigate "http://www. Syntax: Variable=object hierarchy. Syntax: Variable =object hierarchy. It can be used for getting any object's.WinList("From").co.WinComboBox("Fly From:").WinComboBox("Fly From:").exist(time in seconds) Ex: Window("Flight Reservation").B. Syntax: variable=object hierarchy.google.navigate "URL" Ex: Browser("Yahoo!"). Syntax: Object hierarchy.Select "12572 GetVisibletext: It returns Text from the specified area.GetContent Ex: x=Window("Flight Reservation").Exist(5) 26 . Window("Flight Reservation").getvisibletext Ex: x=Window("Flight Reservation").GetContent msgbox x Exist property: It checks whether the object is available or not. Syntax: object hierarchy.GetROProperty ("width") msgbox x Navigate Method: It opens a specified URL in the Browser.GetItemsCount msgbox x Getcontent: It returns all items from a combobox.GetVisibleText msgbox x GetRoproperty: It returns current object property value. any property value.in" Getitemscount: It returns number of items in a combobox.getroproperty ("property name") Ex: x=Window("Flight Reservation").Dialog("Flights Table"). Syntax: Variable = object hierarchy.WinEdit("Tickets:").
Accessibility check point 7. 27 . 1. Inserting Output Values 3. There are several methods available in QTP for enhancing the TEST. Data base check point 6. Inserting Check Points 2. we have to enhance the test in order to Test the AUT with respect to requirements. Page check point 10. Inserting Transaction Points:(Start and End) Inserting Checkpoints Check point is a verification point. Generating Steps through Step Generator 8. Adding Comments 4. Synchronization 6. XML Check point (from Resource) 9. we can insert these checkpoints through standard checkpoint. There are 11 Checkpoints available in QTP: 1. Inserting Flow Control Statements 5.Enhancing Tests After generating the basic test. it takes expected result from the user and compares with actual results during execution and provides test results. Standard check point 2. Parameterization 7. Image checkpoint 11. Text area check point 4. XML Check point (from Application) 8. Table checkpoint Note 1: From 6 to 11 checkpoints are only for Web. Note 2: From 9 to 11 checkpoints are hidden checkpoints. Bit map check point 5. Text check point 3.
Through Active screen. ignore spaces.) We can select one or more options > click ok & stop Recording. Note: We can insert standard checkpoints in 3 ways. Navigation for Editing standard checkpoint Select Checkpoint statement and right click > choose checkpoint properties option > modify the value > click Ok. text not displayed. 2) Text Checkpoint: It Checks object's text property value in different ways. We can use this checkpoint for checking any property value. Through keyword view. 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. Standard Checkpoint: It checks object property values. Navigation: Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint > Show the object > click ok > Select options (Match case. 28 . 3) Text Area Checkpoint: It checks the text area present in the application. 1. 2. 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 Deleting standard checkpoint: Select Checkpoint statements and right click > choose delete option. Through expert view.1. exact match. 3.
Navigation: Keep tool under Recording mode > Insert menu> Checkpoint > Text area checkpoint > Mark the area of text > select one or more options (Match case. Result Criteria: a) If item is available but not according to W3C rules then fail. 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. It is a configurable checkpoint.) Click ok and stop recording. 5. exact match. c) If an item is not available then result would be pass 29 . we can customize. ignore spaces. we can compare complete bitmaps as well as part of the bitmaps. according to our requirements. 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. 4. text not displayed. 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. 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. b) If an item is available. Note: here we do not need to put tool under Recording mode and we do not need AUT since data is from backend. according to W3C rules then Pass. 6. Database checkpoint: It checks Content of the back end Database. Bitmap checkpoint: It compares bitmaps.
Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint > Standard checkpoint >show the web page > click ok > click ok > stop recording. Table checkpoint: It checks content of the web tables. Images and Loading time in a web page. XML Check point (from Resource) It checks content of the XML file. 30 . XML Check point (from Application) It checks content of the XML file. and then we can go for inserting xml checkpoint from resource. Page checkpoint: It checks number of Links. 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. Note: 2. Navigation: Keep tool under Recording mode under web environment > Insert menu > checkpoint > standard checkpoint >show the web table > click ok >stop recording. Navigation: Keep tool under Recording mode in web environment > insert menu > checkpoint (from application)> show the xml pages >click ok > stop Recording. we can insert this through standard checkpoint. It is a hidden checkpoint. If XML file is an individual and path available. Note: 1. 8. separate path is not available then we can choose inserting XML checkpoints from application. 11. Navigation: Insert menu > checkpoint >xml checkpoint (from resource) > browse path of the XML File > click ok > click ok. 9. If XML file is part of web application.7. Image checkpoint: It checks Image property values. 10.
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. 31 .> check in runtime table after running it. Text output value 3. 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. 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. Text area output value 4. It is stored in run time data table. it is located in QTP result window and can be retrieved later.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. Standard output value 2. 2) Text output value: We can use Text output values to output text strings displayed in an application. Database output value 5. 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. Types of Output Values: 1.
4) Database output value: We can use Database output values to output the value of the contents of database cells. 6) XML output Value (From Resource): We can use XML output values to output the values of documents.. Navigation: Insert menu >output value> XML output value from resource > browse path of the XML file > click ok > select elements >click ok. 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. XML elements in XML 32 . 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.3) Text Area output value: We can use text area output values to output text strings displayed within a defined area of the screen. 5) XML output value (from application): we can use XML output values to output the values of XML elements in XML documents. Navigation: Insert menu> output value > Database output value> choose specify SQL statements manually >click next >click create >Select Machine Data source > Select Driver (QT_flight32) > click ok > enter SQL statement (select *from orders) > click finish > select data cells > click ok > Run and it will capture and see the results in run time table.
Use Apostrophe (') before the statement 2. 33 . We can insert VB script conditional statements and loop statements for applying the logic. In VB script there are 2 types of conditional statements and four types of loop statements available.Adding Comments Purpose of Comments: o o For making the script understandable For making the Script Disable from execution Syntax: 1. Use REM Command with single space before the statement Comment a Block of Statements: Navigation: Select block of statements > Edit menu> Advanced> Comment block Or After selecting block of statements use shortcut key Ctrl+M Uncomment a block of statements: Navigation: Select comment block>Edit menu> Advanced>Uncomment block Or After selecting comment block. Use shortcut key ctrl+shift+M Inserting Flow Control Statements QTP adapted VB script engine for applying programming logic to tests.
Syntax: Wait(time in seconds) Note: If we insert wait statements QTP waits up to maximum time even though operation is completed. that time we may not get proper execution and results. Inserting Wait statements. after completion of the current operations. 34 . Inserting Synchronization points. Where Synchronization is required: During test execution QTP gives instructions one by one with same speed.Synchronization It is a process of matching the speeds of both QTP and AUT in order to get proper execution and results. There are several methods available in QTP for synchronization. 1. 4. Increasing Tool default synchronization time.waitproperty "property name". 3. 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: object hierarchy.value. 2. Sync Method (Only for WEB) 5. Inserting Synchronization point: 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 Mille seconds>click ok>Stop recording. but AUT takes less time for some operations execution and more time for some operations execution. it does not wait up to maximum time. it goes to next step immediately. In order to get proper results in between QTP & AUT synchronization is required.time in milli seconds. Note: if we insert Synchronization points.
Page("Yahoo! Toolbar"). Above two are local features but wait statement is Vbscript feature.StartTransaction "name of the transaction" ------statements ---------------services. Suppose in our test one or more statements only are taking more time for execution then selecting "Inserting synchronization method" is better. 35 . It is a performance concept but QTP supports measuring transaction time per user only. Syntax: Object Hirearchy.EndTransaction "name of the transaction" Note: We can insert multiple transactions points in a test. Inserting Transaction Points We can insert Transaction points for measuring Transaction time. 2. Suppose in our test more statements are taking more time for execution then selecting "increasing tool time out" . Sync Method: (only for WEB) Waits for the browser to complete current navigation. 3. even though some drawbacks are there in using wait statement.Increasing Tool default synchronization time: Navigation: File>settings>run tab>increase object synchronization time out>apply>ok Note: If we increase QTP tool default time that can be applied for all statements in the test. After completion of one statement execution it goes to next statement immediately.Sync Selecting an appropriate Method: 1. it is better to use wait statement in functions.Sync Ex: Browser("Yahoo! Toolbar"). but QTP does not wait up to maximum time unnecessarily. Syntax: Services.
").WinEdit("Edit"). Through Loop Statements: We can use loop statements for passing sequential numbers & Logical Numbers. 1. Types of Parameterization: We can parameterize tests in several ways.Set "ON" Window("Flight Reservation"). For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory Window("Flight Reservation").WinButton("Button").WinButton("OK").exe" 36 .Dialog("Open Order"). oracle etc).Dialog("Open Order").Click Window("Flight Reservation"). Getting Test Data from front end objects. Note: We can't generate Strings. 1. Fetching Test Data directly from Databases (MS Acess.Activate Window("Flight Reservation"). For x=1 to 3 Agent =inputbox("enter an Agent Name") Password=inputbox("enter a password") invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a. through this concept we can pass multiple values. Data Driven Testing: Testing the Same operation with multiple sets of test data. 6. Fetching Test Data directly from External files (Flat files & Spreadsheets) 5. We use parameterization in Data Driven Testing.WinCheckBox("Order No. Through Loop Statements 2.Dialog("Open Order"). Dynamic Test Data Submission 3.Dynamic Test Data Submission: Through Loop Statements we can give strings also but every time user has to enter data.Click Next 2.Parameterization Passing parameters.Set orderno Window("Flight Reservation"). Through Data Table 4.
Importing test data from Data bases.WinEdit("Password:"). we can use Data Table for Data Driven Testing.WinButton("OK"). It has 3 types of usage a. Through Data Table: QTP adds one data table (Spreadsheet) for every test.WinEdit("Agent Name:"). Sheet id) Example: agent=datatable("agent". Entering test data directly into data table and use.1) invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.WinEdit("Password:").Close Next 3.Activate Dialog("Login").) Run the test.SetSecure pwd Dialog("Login"). Importing test data from external Flat files c.WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Agent Name:").WinButton("OK"). Agent = Datatable("Agent".1) Pass parameters.1) pwd=Datatable ("Password".exe" Dialog("Login").SetSecure password Dialog("Login").WinEdit("Agent Name:"). A.Click Window("Flight Reservation").Click Window("Flight Reservation").Set Agent Dialog("Login").Activate Dialog("Login"). Steps: Generate the basic test>open data table(View>Data Table) Click on column header>enter the name of the field (like this we can create number of columns) > Enter Data>connect the data to test (variable=datatable("column name".Dialog("Login"). Importing test data from external Spread sheets d.Close 37 . Entering test data directly into data table and use b.Type micTab Dialog("Login").Type micTab Dialog("Login").
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. but first we have to create /get the DSN(Data source Name)& we have to use SQL Commands. 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. 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. 1. Fetching Test Data directly from Flat files 5). by using the DSN we can get data for number of tests. c. Note: DSN Creation is one time activity. Importing test data from Data bases: Through Data table we can import Test Data from Data bases. 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. Creating a Test Database: open MS Access (or we can use any other database). 4. Entering Data into Tables: Select table>enter the data. Fetching Test Data directly from Excel Sheets 6) Fetching Test Data directly from Databases 38 . Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension.b.
WinButton("OK"). We can create as many files as we want and we can change values of variables.WinEdit("Password:").Activate Dialog("Login"). Types of Environment variables: 1. 39 . we can access from all tests but these are designed as read only.Run ProductDir & app Dialog("Login"). Built in variables: These are system defined variables.SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407" Dialog("Login"). User defined variables: Variables that we predefine in the active external environment variables file. 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.WinEdit("Agent Name:").Click Creating user defined environment variables: Navigation: File > settings > Environment > select variable type as user defined > click add icon (+) > enter variable name & Value > click ok (like this we can create number of variables) > click export > browse path & enter file name. 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. If we declare as local variables in number of tests. save with xml extension > click ok.Set "pavan" Dialog("Login").Environment Variables in QTP These are global variables.exe" Systemutil. modifications are difficult. 2. if we want to use some variables globally (From number of tests) declaring as global variables is better.
40 .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.
Splitting an action: Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name & action 2 name.Actions Action: A Set of Statements for performing a Task or Tasks. Purpose of Actions: For better understandability For reusing components Types of Actions: 1) Non Re usable actions 2) Re usable actions 3) External actions Operations on Actions: • Creating Actions • Splitting Actions • Renaming Actions • Deleting Actions • Calling an Action • Copying an Action • Making an Action Reusable/Non Reusable Creating an Action: Insert>call to new action>enter name of the action>click ok Steps: 1. Steps: 1. insert. 41 . Generate total test in the default action 2.delte) 2. We divide our test into actions to streamline the process of testing. Split into meaningful actions. Prepare Scripts for those actions. Create required actions(ex login.
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
(Fundamentals and Features)
1) Introduction 2) Comments 3) VB Script Variables 4) VB Script Data Types 5) VB Script Operators 6) Input/Output Operations 7) Constants 8) Conditional Statements 9) Loop through Code 10) VB Script Procedures 11) Procedures 12) VBScript syntax rules and guidelines 13) Errors
1.0 Introduction
• • • VBScript is a scripting language. A scripting language is a lightweight programming language. VBScript is a light version of Microsoft's programming language Visual Basic.
When a VBScript is inserted into a HTML document, the Internet browser will read the HTML and interpret the VBScript. The VBScript can be executed immediately, or at a later event. Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information Service. 1.1 Windows Script Host (WSH) It is a Windows administration tool. WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium Editions and higher versions.
A Windows script is a text file. We can create a script with any text editor as long as we save our script with a WSH-compatible script extension (.js, vbs, or .wsf). The most commonly available text editor is already installed on our computer — Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++, or Visual InterDev. 1.2 Creating a script with Notepad 1. Start Notepad. 2. Write your script. For example purposes, type Msgbox "Hello VB Script" 3. Save this text file with a .vbs extension (instead of the default .txt extension). For example, Hello.vbs 4. Navigate to the file you just saved, and double-click it. 5. Windows Script Host invokes the VB Script engine and runs your script. In the example, a message box is displayed with the message "Hello VB Script"
Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files. which invokes the associated script engine to interpret and run the file. the engine that interprets and runs the script code is built into Internet Information Services (IIS). such as Perl.4 Available Script Engines Generally. These extensions are registered with Windows. 1. We can use other script engines. the engine component that interprets and runs the script code is loaded by the Web browser. and Python. REXX. we write scripts in either Microsoft JScript or VBScript.js extension. either in an HTML page (on the client side) or in an ASP page (on the server side). 2000 and Millennium Editions. When we run one of these types of files. a stand-alone script written in VBScript has the . such as Internet Explorer.1. A stand-alone script written in JScript has the . In the case of a script embedded in an ASP page. In the case of a script embedded in an HTML page. 45 .3 Hosting Environments and Script Engines Scripts are often embedded in Web pages. with Windows Script Host. Windows starts Windows Script Host.vbs extension. the two script engines that ship with Microsoft Windows 98.
2 Comment/Uncomment a block of statements o Select block of statement and use short cut key Ctrl + M (for comment) o Select comment block and use short cut key Ctrl + Shift + M (for uncomment) 46 .1 Syntax Rem comment (After the Rem keyword. 2. 2. We can use comments for making one or more statements disable from execution.) Or Apostrophe (') symbol before the comment 2.0 Comments The comment argument is the text of any comment we want to include.0 Purpose of comments: o o We can use comments for making the script understandable.2. a space is required before comment.
Left. That is not generally a good practice because we could misspell the variable name in one or more places. 3. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. Option Explicit ' Force explicit variable declaration. 3.1 Declaring Variables We declare variables explicitly in our script using the statement. MyInt = 10 ' Undeclared variable generates error. For example: Dim x. 3. the Public We can also declare a variable implicitly by simply using its name in our script. 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. Dim MyVar ' Declare variable. Top. Right Dim statement.2 Option Explicit Forces explicit declaration of all variables in a script.0 VB Script Variables 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. Bottom.3 Naming Restrictions for Variables 47 .3. causing unexpected results when our script is run. and the Private statement. For that reason. MyVar = 10 ' Declared variable does not generate error.
Must be unique in the scope in which it is declared.7 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. At procedure level. When we declare a variable within a procedure. a variable exists only as long as you are in the procedure. 3. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. For example: B = 200 City = "Hyderabad" 3. except that the declaration of an array variable uses parentheses () following the variable name. we make it recognizable to all the procedures in our script. A variable containing a series of values. 3. Cannot contain an embedded period. 3. and it has scriptlevel scope. Example: Dim A(3) 48 . A variable name: • • • • Must begin with an alphabetic character.6 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. Array variables and scalar variables are declared in the same way. only code within that procedure can access or change the value of that variable If we declare a variable outside a procedure. This is a script-level variable.5 Life Time of Variables o o o The lifetime of a variable depends on how long it exists. is called an array variable. Must not exceed 255 characters.Variable names follow the standard rules for naming anything in VBScript.4 Scope of Variables o o o A variable's scope is determined by where you declare it.
the first number is always the number of rows. However. For example: Dim MyArray() 49 .Although the number shown in the parentheses is 3. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. We assign data to each of the elements of the array using an index into the array. We can have as many as 60 dimensions. This is called a dynamic array. although most people can't comprehend more than three or four dimensions. the data can be retrieved from any element using an index into the particular array element you want. 10) In a two-dimensional array. data can be assigned to the elements of an array as follows: A(0) A(1) A(2) A(3) = = = = 256 324 100 55 Similarly. Beginning at zero and ending at 10. You can have as many as 60 dimensions. Arrays aren't limited to a single dimension. so this array actually contains 4 elements. 3. all arrays in VBScript are zerobased. no size or number of dimensions is placed inside the parentheses. In the following example. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5. although most people can't comprehend more than three or four dimensions.8 Dynamic Arrays We can also declare an array whose size changes during the time our script is running. the second number is the number of columns. for a dynamic array.
The following table shows subtypes of data that a Variant can contain. Contains integer in the range -2. and the Variant behaves in a way that is most appropriate for the data it contains.203. -922. but uses the Preserve keyword to preserve the contents of the array as the resizing takes place. a Variant can make further distinctions about the specific nature of numeric information. In the following example.648 to 2.5808 to 922. Because Variant is the only data type in VBScript. we lose the data in the eliminated elements.768 to 18.104.22.1687. Contains integer in the range 0 to 255. ReDim sets the initial size of the dynamic array to 25. we can have numeric information that represents a date or a time. ReDim MyArray(25) ReDim Preserve MyArray(30) There is no limit to the number of times we can resize a dynamic array.337.483. Contains either True or False. For example. although if we make an array smaller. When used with other date or time data. 4. A subsequent ReDim statement resizes the array to 30.685. Subtype Empty Null Boolean Byte Integer Currency Long Description Variant is uninitialized. These different categories of information that can be contained in a Variant are called subtypes.337. A Variant is a special kind of data type that can contain different kinds of information.477.483. we can just put the kind of data we want in a Variant.147. depending on how it is used. the result is always expressed as a date or a time. Most of the time.1 Variant Subtypes Beyond the simple numeric or string classifications. Value is 0 for numeric variables or a zerolength string ("") for string variables. 4.685. 50 .477.5807.ReDim AnotherArray() To use a dynamic array. it is also the data type returned by all functions in VBScript. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. Variant intentionally contains no valid data. you must subsequently use ReDim to determine the number of dimensions and the size of each dimension.647. Contains integer in the range -32.0 VB Script Data Types VBScript has only one data type called a Variant.
Contains a variable-length string that can be up to approximately 2 billion characters in length. 9999.79769313486232E308 to -4.402823E38 for positive values. 51 . Contains a double-precision.94065645841247E-324 to 1.Single Double Date (Time) String Object Error Contains a single-precision. Within parentheses. 4. that is. 100 to December 31. Contains an object. VBScript has a full range of operators. concatenation operators. Operations within parentheses are always performed before those outside. Comparison operators all have equal precedence. the VarType function returns information about how your data is stored within a Variant.401298E-45 to 3.1 Operator Precedence When several operations occur in an expression. however. Contains a number that represents a date between January 1.401298E-45 for negative values. Contains an error number. comparison and logical operations. each part is evaluated and resolved in a predetermined order called operator precedence. arithmetic operators are evaluated first. We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. comparison operators. comparison operators are evaluated next. they are evaluated in the left-to-right order in which they appear.94065645841247E-324 for negative values. standard operator precedence is maintained. 4. We can use conversion functions to convert data from one subtype to another. 1. including arithmetic operators. In addition. Arithmetic and logical operators are evaluated in the following order of precedence.402823E38 to -1. floating-point number in the range -1.79769313486232E308 for positive values. 5.0 VB Script Operators Operators are used for performing mathematical. floating-point number in the range -3. and logical operators. When expressions contain operators from more than one category. and logical operators are evaluated last.
Divides two numbers and returns only the remainder. 3) One expression is numeric and Add. Operator 1) = 2) <> 3) < 4) > Description Equal to Not equal to Less than Grater than Operator 5) <= 6) >= 7) Is Description Less than or equal to Greater than or equal to Object equivalence Description Raises a number to the power of an exponent. 2) Both expressions are strings Concatenate. Divides two numbers and returns a floating-point result. Sums two numbers.5 Logical Operators 52 . If Then 1) Both expressions are numeric Add. 2) Concatenation Operator (&) 4. Forces string concatenation of two expressions.2 Arithmetic Operators: Operator 1) Exponentiation Operator (^) 2) Multiplication Operator (*) 3) Division Operator (/) 4) Integer Division Operator (\) 5) Mod Operator 6) Addition Operator (+) 7) Subtraction Operator (-) 8) Concatenation Operator (&) 4. Divides two numbers and returns an integer result.3 Comparison Operators Used to compare expressions.4 Concatenation Operators Operator 1) Addition Operator (+) Description Sums two numbers.4. 4. Multiplies two numbers. the other is a string Forces string concatenation of two expressions. Finds the difference between two numbers or indicates the negative value of a numeric expression.
Performs a logical conjunction on two expressions. "MsgBox Example") ' MyVar contains either 1 or 2. waits for the user to input text or click a button.Operator 1) Not 2) And 3) Or 4) Xor 5) Eqv 6) Imp Description Performs logical negation on an expression.2 MsgBox Function Displays a message in a dialog box. we can create string or numeric constants with meaningful names and assign them literal values. depending on which button is clicked. 7.1 Creating Constants We create user-defined constants in VBScript using the Const statement. Performs a logical disjunction on two expressions. Using the Const statement. and returns a value indicating which button the user clicked.1 InputBox Function Displays a prompt in a dialog box. Syntax result= Not expression result= expression1 expression2 result= expression1 expression2 result= expression1 expression2 result= expression1 expression2 And Or Xor Eqv result= expression1 Imp expression2 6) Input/Output Operations 6. waits for the user to click a button. 65. Performs a logical equivalence on two expressions. 7) VB Script Constants A constant is a meaningful name that takes the place of a number or string and never changes. 53 . Const statement Declares constants for use in place of literal values. Performs a logical implication on two expressions. and returns the contents of the text box. Example: Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 6. Example: Dim MyVar MyVar = MsgBox ("Hello World!". Performs a logical exclusion on two expressions.
..1....Else The If. we must use the multiple-line (or block) syntax. The following conditional statements are available in VBScript: 1) If…Then…Else Statement 2) Select Case Statement 8.Else statement..1. depending on the result. x= 27 8) Conditional Statements We can control the flow of our script with conditional statements and looping statements.. 8..1 Making Decisions Using If.Then.. We declare multiple constants by separating each constant name and value with a comma.1 Running a Statements if a Condition is True (single statement) To run only one statement when a condition is True.2 Running Statements if a Condition is True (multiple statements) To run more than one line of code. For example: Const price= 100. Represent Date literals and time literals by enclosing them in number signs (#). we can write VBScript code that makes decisions and repeats actions. This syntax includes the End If statement. If. Using conditional statements.Else statement is used to evaluate whether a condition is True or False and. to specify one or more statements to run.Then. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 8." Const MyAge = 49 Const CutoffDate = #6-1-97# Note that String literal is enclosed in quotation marks (" ").Else statements can be nested to as many levels as you need.. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another.Then... use the single-line syntax for the If....Then. Dim x x= 20 54 .Example: Const MyString = "This is my string. city= "Hyderabad"..
. the other block to run if the condition is False.1.Else statement to define two blocks of executable statements: one block to run if the condition is True.1.4 Deciding Between Several Alternatives A variation on the If.C...Then..3 Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If.Reddy" msgbox "x value is: "&x msgbox "Bye Bye" End If 8.. Adding ElseIf clauses expands the functionality of the If..C....Reddy" Msgbox "X is a Big Number" Msgbox "X value is: "&X Else Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&X End If 8. Example: Dim x x= Inputbox (" Enter a value") If x>0 and x<=100 Then Msgbox "Hello G. Example: Dim x x= Inputbox (" Enter a value") If x>100 Then Msgbox "Hello G.Else statement allows us to choose from several alternatives..Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" 55 .If x>10 Then msgbox "Hello G..Then..Then.Else statement so we can control program flow based on different possibilities.C.
5 Executing a certain block of statements when two / more conditions are True (Nested If.Else End If End If End If Msgbox "Hello Sir" Msgbox "X is a Grand Number" 8.Then..2 Making Decisions with Select Case The Select Case structure provides an alternative to If.ElseIf for selectively executing one block of statements from among multiple blocks of statements. Example: Option explicit Dim x. 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) 56 ..Else statement..1. Operation. A Select Case statement provides capability similar to the If.C. Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") If state= "AP" Then If Region= "Telangana" Then msgbox "Hello G..y. but it makes code more efficient and readable..Then...Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9" End End End End If If If If 8..) Example: Dim State...
Reddy" msgbox "Wrong Operation" Case "div" Case "expo" End Select 8.3.y values is "&Result Case "sub" Result= x-y Msgbox "Hello G.3.C. Even number or Odd number? Dim num num=inputbox ("Enter a number") 57 .C.Reddy" Msgbox "Addition of x.y values is "&Result Case Else Msgbox "Hello G.Reddy" Msgbox "Substraction of x.y values is "&Result Case "mul" Result= x*y Msgbox "Hello G.y values is "&Result Case "mod" Result= x mod y Msgbox "Hello G.Reddy" Msgbox"Exponentation of x.C.1 Write a program for finding out whether the given year is a leap year or not? Dim xyear xyear=inputbox ("Enter Year") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 8.y values is "&Result Result= x/y Msgbox "Hello G.Reddy" Msgbox "Mod of x.Msgbox "Hello G.2 Write a program for finding out whether the given number is.Reddy" Msgbox "Division of x.C.y values is "&Result Result= x^y Msgbox "Hello G.C.C.C.Reddy" Msgbox "Multiplication of x.3 Other Examples 8.
6 Read any Four digit number and display the number in reverse order? Dim num.t. calculate & display the sum of the number or display Error message if the number is not a four digit number? Dim num. 3) sum=sum+num mod 10 num=num/10 num= left (num. r. 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number. t=time in years.3.num2.3 Read two numbers and display the sum? Dim num1. sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10 num=num/10 num= left (num.4 Read P.3. sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require msgbox ("Sum is " &sum) 8.5 Read Four digit number.3.rev num= inputbox("Enter a number") 58 .3. r= rate of interest msgbox ("Simple Interest is " &si) 8.T. 2) sum=sum+num mod 10 num=num/10 num= left (num. you entered is not a 4 digit number" End If 8.If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 8.R values and Calculate the Simple Interest? Dim p. si p=inputbox ("Enter Principle") t=inputbox ("Enter Time") r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount.
c.p.7 Read 4 subjects marks.m. calculate the Total marks and grade? (a) If average marks Greater than or equal to 75.3) rev=rev*10 + num mod 10 num=num/10 num= left(num. you entered is not a 4 digit number" 8. then grade is First c) If average marks Greater than or equal to 50 and less than 60 . otherwise 'no grade fail') Dim e. grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 .3.If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num.2) rev=rev*10 + num mod 10 num=num/10 num= left(num. tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" 59 . then grade is Second d) If average marks Greater than or equal to 40 and less than 50 . then grade is Third e) Minimum marks 35 for any subject.1) rev=rev*10 + num mod 10 Else End If msgbox "Reverse Order of the number is "&rev msgbox "Number.
. Fail" End End End End If If If If 8.3.else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade.n n=Inputbox ("Enter a Vaule") For num= 1 to n step 2 msgbox num Next 8.3. n.writeline num myfile.n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 8.10 display natural numers up to n and write in a text file? Dim num.filesystemobject") set myfile=fso. 8.opentextfile ("E:\gcr.n n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 8. fso.3.9 Display Even numbers up to n? Dim num.. sum n= inputbox ("Enter a Value") sum=0 For num= 1 to n step 1 60 .12 Display Natural numbers sum up to n? (using For.Next Loop) Dim num. myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting. n.txt". true) myfile.8 Display Odd numbers up to n? Dim num.close Next 8.11 Display Natural numbers in reverse order up to n? Dim num.
16 Verify weather the entered 10 digit value is a numeric value or not? Dim a.14 Display Natural numbers sum up to n? (using Do.. sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 8. 8.. 9.1) d2=mid (num.z. 5. 2.. n.Loop) Dim num.y. 3. len d7=mid (num.13 Display Natural numbers sum up to n? (using While.1) d10=Right (num. len d6=mid (num. 7. len d3=mid (num.. len d9=mid (num. 6.x. 4.Next sum= sum+num msgbox sum 8. len d8=mid (num.. len (1)) (1)) (1)) (1)) (1)) (1)) (1)) (1)) 61 . sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 8. len d5=mid (num.Until.. sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum 8. n.num num=Inputbox ("Enter a Phone Number") d1= left (num. len d4=mid (num.Wend Loop) Dim num.15 Write a Function for Natural Numbers sum up to n? Function NNumCou (n) Dim num.
8. len d9=mid (num.x.17 Verify weather the entered value is a 10 digit value or not and Numeric value or not? (using multiple if conditions) Dim a. len d8=mid (num. len d5=mid (num. 4. len d7=mid (num. 7.y.z. len d3=mid (num.1) d10=Right (num. len (1)) (1)) (1)) (1)) (1)) (1)) (1)) (1)) If len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then Msgbox "It is NOT valid Number " End If 62 .num num=Inputbox ("Enter a Phone Number") d1= left (num.If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If 8. len d4=mid (num.1) d2=mid (num. len d6=mid (num. 6. 2. 3. 5. 9.
.9) Looping Through Code o Looping allows us to run a group of statements repeatedly.. we can use this below syntax: 63 ..Wend: Loops while a condition is True.1 Using Do Loops We can use Do..Loop: Loops while or until a condition is True. o Others repeat statements until a condition is True.1. o There are also loops that repeat statements a specific number of times. While..1 Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True a) Do While condition Statements --------------------Loop Or. 9. 9.Loop statements to run a block of statements an indefinite number of times. For... For Each. The statements are repeated either while a condition is True or until a condition becomes True..Next: Repeats a group of statements for each item in a collection or each element of an array. The following looping statements are available in VBScript: • • • • Do.Next: Uses a counter to run statements a specified number of times. o Some loops repeat statements until a condition is False...
Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G. we can use this below syntax: 64 . we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G. we can use this below syntax: d) Do Statements --------------------Loop Until condition Or.Reddy" Msgbox "Hello QTP" Loop b) Do Statements --------------------Loop While condition Example: Dim x x=1 Do Msgbox "Hello G.1.C.Reddy" Msgbox "Hello QTP" Loop Or.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 9.2 Repeating a Statement Until a Condition Becomes True c) Do Until condition Statements --------------------Loop Or.C.C.
Syntax: While condition Statements --------------------Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G...Reddy" msgbox "Hello QTP" Wend 9.Example: Dim x x=1 Do Msgbox "Hello G.C.C.2 While.Wend Statement Executes a series of statements as long as a given condition is True.C.. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G..Reddy" Msgbox "Hello QTP" x=x+1 Loop Until x=5 9.3 For.Reddy" Next 65 .Next Statement Repeats a group of statements a specified number of times.
x (3) a=20 b=30 x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next Example: MyArray = Array("one". or expressions that are passed by a calling procedure). 11..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.Next Statement Repeats a group of statements for each element in an array or collection. Syntax: Sub procedure and the 66 . A Sub procedure can take arguments (constants."two". the Function procedure."five") For Each element In MyArray msgbox element Next 10) VB Script Procedures In VBScript. Syntax: For Each item In array Statements Next Example: Dim a.. there are two kinds of procedures. If a Sub procedure has no arguments.b."four". variables.9. its Sub statement must include an empty set of parentheses ()."three".4 For Each.
2 Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C. but can also return a value. A Function procedure is similar to a Sub procedure." End Sub Example: 2 11. A Function returns a value by assigning a value to its name in one or more statements of the procedure. its Function statement must include an empty set of parentheses. If a Function procedure has no arguments. or expressions that are passed to it by a calling procedure). A Function procedure can take arguments (constants.".Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1. argument2) Statements --------------------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F. The return type of a Function is always a Variant. 67 . variables.
Arguments serve as placeholders for the data we want to pass into our procedure. separated by commas.32) * 5 / 9 End Function Example: 2 Function cal(a. Any arguments are placed inside these parentheses.Syntax: Function Procedure name () Statements --------------------End Function Or Function Procedure name (argument1.b.c) cal = (a+b+c) End Function 11. o o 68 .3 Getting Data into and out of Procedures o o Each piece of data is passed into our procedures using an argument. argument2) Statements --------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees . We can name our arguments any valid variable name. parentheses must be included after the name of the procedure. When we create a procedure using either the Sub statement or the Function statement.
69 . One uses the Call statement in the code." To call a Sub procedure from another procedure. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees. type the name of the procedure along with values for any required arguments. Both do exactly the same thing. each separated by a comma. Call MyProc(firstarg. but if you do use it. secondarg) MyProc firstarg.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.11. you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. The Call statement is not required. the other doesn't. secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used.
11) VB Script Built in Functions 1) Asc Function 'Returns ANSI character code corresponding to first letter in a string Dim val val="hyderabad" val=Asc(val) msgbox val 2) Chr Function 'Returns the character associated with the specified ANSI character code. Dim val val=65 val=Chr(val) msgbox val 'Output: A 3) Date Function It returns current system Date Dim myDate myDate=Date msgbox myDate 70 .
#01-05-2010#) msgbox var(0) 'output: 100 msgbox var(1) 'output: India msgbox var(2) 'output: 01/05/2010 71 .4) Abs Function It returns obsolute value of the given number. 300) msgbox var(0) 'output: 100 msgbox var(1) 'output: 200 msgbox var(2) 'output: 300 'List of mixed values var=Array(100.56 num=Abs(num) msgbox num 'Output: 157."India".56 Note: It provide positive value 5) Array Function We can enter list of values using this function Ex: Dim var 'List of strings var=Array("Hyderabad".56 num=Abs(num) msgbox num 'Output: 157.56 num=-157. Dim num num=157.200. "Nellore") msgbox var(0) 'output: Hyderabad msgbox var(1) 'output: Chennai msgbox var(2) 'output: Nellore 'List of numeric values var=Array(100."Chennai".
6) IsArray Function It checks weather the given variable is an Array or not Dim var1. var2.x myDate=100 x=IsDate(myDate) msgbox x 'Output: False myDate="India" x=IsDate(myDate) msgbox x 'Output: False myDate=#10/05/2010# x=IsDate(myDate) msgbox x 'Output: True myDate=#10-05-2010# x=IsDate(myDate) msgbox x 'Output: True myDate=#10-05-10# x=IsDate(myDate) 72 .x 'List of strings var1=Array("Hyderabad"."Chennai". "Nellore") x=isArray(var1) 'It returns True/False like Result msgbox x x=isArray(var2) msgbox x 7) IsDate It checks weather the given value is Date type data or not Examples: Dim myDate.
Date2.date2) 'it considers days only msgbox x' It subtracts date1 from date2 Note: through this function.x val="100" x=Isnumeric(val) msgbox x 'Output: True val=100 x=Isnumeric(val) msgbox x 'Output: True 73 .x Date1=#10-10-2008# Date2=#10-09-2010# x=DateDiff("d".msgbox x 'Output: True myDate=10-05-2010 x=IsDate(myDate) msgbox x 'Output: False 8) DateDiff Function It provides difference between two dates.date2)' m for month msgbox x' It subtracts date1 from date2 x=DateDiff("y".date2) 'd for day msgbox x' It subtracts date1 from date2 x=DateDiff("m". based on interval (day/month) Dim Date1. 9) IsNumeric It checks weather the given value is numeric or not and It provides True/False like Result Example: Dim val. we can day or month wise diffrence only. date1. date1. date1.
x=Isnumeric(500) msgbox x 'Output: True x=Isnumeric("India") msgbox x 'Output: False 10) Len Function It finds legngh of the String Example: Dim val.x val="Hyderabad" x=Len(val) msgbox x 'Output: 9 val=100 x=Len(val) msgbox x 'Output: 3 val="Hydera100" x=Len(val) msgbox x 'Output: 9 val="hy$@*de" x=Len(val) msgbox x 'Output: 7 val="100" x=Len(val) msgbox x 'Output: 3 val=#10-10-2010# x=Len(val) msgbox x 'Output: 10 x=Len("Krishna") 74 .
3) msgbox x ' Output: H92 x=Left(9247837478.x val="Hyderabad" x=Left(val.3) msgbox x ' Output: Hyd val="9247837478" x=Left(val.Lengh) Example: Dim val.3) msgbox x ' Output: 10/ 75 .1) msgbox x ' Output: 9 val="H92yderabad" x=Left(val.5) msgbox x ' Output: 92478 val=#10-10-10# x=Left(val.msgbox x 'Output: 7 x=Len(Krishna) msgbox x 'Output: 0 x=Len() msgbox x 'Output: Error 11) Left Function Returns a specified number of charectors of a given string from left side Syntax: variable=Left(string.
12) Right Function Returns a specified number of charectors of a given string from Right side Example: Dim val.3) msgbox x ' Output: bad 76 .1) msgbox x ' Output: 8 val="H92yderabad" x=Right(val.3) msgbox x ' Output: bad val="9247837478" x=Right(val.x val="Hyderabad" x=Right(val.
x val="Hyderabad" x=Mid(Val.5) msgbox x ' Output: 0/2010 14) StrReverse 77 .3) msgbox x ' Output: rab val="Hyderabad" x=Mid(Val.5) msgbox x ' Output: rabad val="9247837478" x=Mid(val.1) msgbox x ' Output: H92yderabad x=Mid(9247837478.5) msgbox x ' Output: 37478 val="H92yderabad" x=Mid(val.6.5.x=Right(9247837478.5) msgbox x ' Output: 37478 val=#10-10-10# x=Right(val.5) msgbox x ' Output: /2010 13) Mid function Returns a specified number of characters of a given string Example: Dim val.5) msgbox x ' Output: 837478 val=#10-10-10# x=Mid(val.
x val="Hyderabad" x=StrReverse(val) msgbox x 'Output dabaredyH val="001" x=StrReverse(val) msgbox x 'Output: 100 val=1002 x=StrReverse(val) msgbox x 'Output: 2001 val=#10-10-10# x=StrReverse(val) msgbox x 'Output: 0102/01/01 x=StrReverse("Hyderabad") msgbox x 'Output: dabaredyH x=StrReverse(100) msgbox x 'Output: 001 15) StrComp Function It compares two string (Binary and textual) If a) Both are equal. returns 1(one) b) String 2 greater than string 1. returns 0(zero) b) String 1 greater than string 2. returns -1 Example: 78 .retuns reverse value of a string Example: Dim val.
1) msgbox x 'Output -1 79 .str2.str2.x str1="India" str2="India" x=StrComp(str1.str2.1) msgbox x 'Output 0 str1="India" str2="Indian" x=StrComp(str1.str2.str2.1) msgbox x 'Output -1 str1="Indian" str2="India" x=StrComp(str1.Dim str1.1) msgbox x 'Output 0 str1=100 str2=101 x=StrComp(str1.str2.str2.1) msgbox x 'Output -1 str1="Indian" str2="Ndia" x=StrComp(str1.1) msgbox x 'Output 0 str1="india" str2="INDIA" x=StrComp(str1.1) msgbox x 'Output 1 str1=100 str2=100 x=StrComp(str1.str2.
16) Lcase function Coverts Upper case values into Lower case Dim val.x val="HYDERABAD" x=Lcase(val) msgbox x 'Output hyderabad val="Hyderabad" x=Lcase(val) msgbox x 'Output hyderabad val="HederabaD" x=Lcase(val) msgbox x 'Output hyderabad val="hyderabad" x=Lcase(val) msgbox x 'Output hyderabad x=Lcase("HYDERABAD") msgbox x 'Output hyderabad 17) Ucase function Coverts Lower case values into Upper case Example: Dim val.x val="HYDERABAD" x=Ucase(val) msgbox x 'Output HYDERABAD val="Hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD 80 .
next nearest value.x num=14.val="HyderabaD" x=Ucase(val) msgbox x 'Output HYDERABAD val="hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD x=Ucase("HYDERABAD") msgbox x 'Output HYDERABAD 18) Round Function Returns the round value of a given value if value decimal point above .5 returns before integer value. Example: Dim num.49" x=Round(num) msgbox x 'Output: 14 num="Hyd" x=Round(num) msgbox x 'Output: Error 19) Trim Function Returns a copy of string without leading spaces Dim val 81 .5 it returns.49 x=Round(num) msgbox x 'Output: 14 num=14.59 x=Round(num) msgbox x 'Output: 15 num="14. below .
val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x VB Script" x=Trim(val) 100" x=Trim(val) 2#$%^" x=Trim(val) VB Script " x=Trim(val) 20) Ltrim Function It removes spaces from left side of a string Dim val val=" msgbox x x=Len(x) msgbox x val="100 x=LTrim(val) msgbox x " VB Script" x=LTrim(val) 82 .
x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val= msgbox x x=Len(x) msgbox x 21) Rtrim It removes spaces from right side of a string Dim val val="VB Script x=RTrim(val) msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x 100 " " 100 VB Script " 2#$%^ " x=LTrim(val) x=LTrim(val) x=LTrim(val) x=RTrim(val) 83 .
b.a.is.Script.") msgbox a(5) 'Output: Scripting b="VB Script is a Powerful scripting Language" a=Split(b) 84 . one-dimensional array containing a specified number of substrings Example: Dim a.x b="VB Script is a Powerful scripting Language" a=Split(b." ") x=IsArray(b) msgbox x 'Output: False x=IsArray(a) msgbox x 'Output: True msgbox a(6) 'Output: Language b="VB.scripting.val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val= msgbox x x=Len(x) msgbox x 2#$%^ " x=RTrim(val) VB Script " x=RTrim(val) 100 x=RTrim(val) 22) Split function Returns a zero-based.Powerful.Language" a=Split(b.".
in the above segment of script. Using variables helps to make our script more readable and flexible 21.5 Indentation: 85 . for example. For example.WaitProperty("items count".page("find a flight:"). the names of the Web site. arrays and objects. because it is a text string that represents a number and not a numeric value.WebList("toDay"). Total_Items.msgbox a(5) 'Output: Scripting b="VB@Script@is@a@Powerful@scripting@Language" a=Split(b. In the following example.weblist("today"). only the property name (first argument) is a text string and is in quotation marks."@") msgbox a(5) 'Output: Scripting b="VBScriptisaPowerfulscriptingLanguage" a=Split(b) msgbox a(5) 'Output: Error 12) VBScript syntax rules and guidelines 21. integers. and edit box are all text strings surrounded by quotation marks.3 Variables: We can specify variables to store strings. For example. which also does not need quotation marks. 2000) 21. VBScript is not case sensitive and does not differentiate between uppercase and lower-case spelling of words. we must add quotation marks before and after the string. object and method names.select "31" 21. 21. The third argument (specifying the timeout) is a numeric value. Web page. Browser("Mercury").4 Parentheses: To achieve the desired result and to avoid errors. The second argument (the value of the property) is a variable and therefore does not have quotation marks.1 Case-sensitivity: By default. in variables. or constants.Select "31" browser("mercury"). it is important that we use parentheses () correctly in our statements. the two statements below are identical in VBScript: Browser("Mercury"). Note that the value 31 is also surrounded by quotation marks.Page("Find a Flight:").2 Text strings: When we enter a value as a text string.Page("Find a Flight:").
or at the end of a statement. These spaces are ignored by VBScript. before the program has begun to be executed. they are VBScript Run-time Errors and VBScript Syntax Errors 13. 21. either at the beginning of a separate line. to make our scripts easier to understand and maintain. 21. VBScript syntax errors occur during the program compilation stage.7 Spaces: We can add extra blank spaces to our script to improve clarity. 13. when variable expressions are being evaluated.1 VBScript Run-time Errors VBScript run-time errors are errors that result when our VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while our script is being executed. File System Operations 86 . and memory is being dynamic allocated.We can indent or outdent our script to reflect the logical structure and nesting of the statements. It is recommended that we add comments wherever possible.6 Comments: We can add comments to our statements using an apostrophe ('). 13) Errors We have two types Errors in VB Script.2 VBScript Syntax Errors VBScript syntax errors are errors that result when the structure of one of our VBScript statements violates one or more of the grammatical rules of the VBScript scripting language.
method syntax with a rich set of properties. To manipulate binary files. contained in the Scripting type library (Scrrun. We may not want to have such overhead. In this case. insert and change the data. Although we can store data in a database.DeleteFolder("E:\Pavan") 3) Copying Folders Set oFSO=createobject("Scripting. and output (read) the data. It allows us to use the familiar object. strDirectory strDirectory = "D:\Pavan" Set objFSO = CreateObject("Scripting. When processing files. methods.FileSystemObject") oFSO. and events to process folders and files. It also enables us to get information about folders. easy-to-access format. the FSO model does not support binary files.CreateFolder(strDirectory) 2) Delete a Folder Set oFSO = CreateObject("Scripting. move. We can also employ the traditional Visual Basic statements and commands. strDirectory 87 . such as their names and the date they were created or last modified. True 4) Checking weather the folder available or not. Examples 1) Create a Folder Option Explicit Dim objFSO. objFolder.File System Object Model: The File System Object (FSO) model provides an object-based tool for working with folders and files. if not creating the folder Option Explicit Dim objFSO. our primary goal is to store data in an efficient. use the FileOpen Function with the Binary keyword.CopyFolder "E:\gcr".Filesystemobject") oFSO. alter. We need to be able to create files. The FSO model makes processing files much easier as well. however. "C:\jvr". or our data access requirements may not call for the extra functionality associated with a fullfeatured database. doing so adds a significant amount of overhead to our application. storing our data in a text file or binary file is the most efficient solution. or to determine if and where particular folders exist. The FSO model.FileSystemObject") Set objFolder = objFSO. and delete folders. The FSO model gives our application the ability to create. objFolder. supports the creation and manipulation of text files through the TextStream object.dll).
DriveLetter Next 6) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.txt") 8) Checking weather the File is available or not.strDirectory = "D:\Pavan" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:\Pavan.FileSystemObject") Set objFile = objFSO.GetDrive("C:") MsgBox "Available space: " & oDrive.CreateFolder(strDirectory) end if 5) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.FileSystemObject") If objFSO.txt") End if 9) Reading Data character by character from a Flat File Set objFSO = CreateObject("Scripting.FolderExists(strDirectory) Then Set objFolder = objFSO. 1) Do Until objFile.FileSystemObject") If objFSO.FileSystemObject") Set oDrive = oFSO.GetFolder(strDirectory) Else Set objFile = objFSO.GetFolder(strDirectory) msgbox strDirectory & " already created " else Set objFolder = objFSO.CreateTextFile("E:\Pavan.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.txt".AtEndOfStream strCharacters = objFile.txt" Set objFSO = CreateObject("Scripting.CreateTextFile("E:\Pavan.Read(1) msgbox strCharacters Loop 88 .Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.AvailableSpace Working with Flat Files 7) Creating a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set colDrives = oFSO. if not creating the File strDirectory="E:\" strFile="Pavan.
Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.txt") txtFilepath.10) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting. dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting.readline s=split (x.FileSystemObject") If objFSO.GetFile("E:\gcr. if available delete the File strDirectory="E:\" strFile="gcr.skipline While myfile.myfile Set fso=createobject("scripting."C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\".Readline msgbox strCharacters Loop 11) Reading data from a flat file and using in data driven testing Dim fso.txt" Set objFSO = CreateObject("Scripting. myFSO. 8.filesystemobject") Set txtFilepath = objFSO."".WinEdit("Agent Name:").SetSecure s(1) Dialog("Login").FileSystemObject") Set objFile = objFSO.exe".atendofline <> True x=myfile.FileSystemObject") Set WriteStuff = myFSO.opentextfile ("F:\Pavan."open" Dialog("Login").Delete() 14) Checking weather the File is available or not.FileExists(strDirectory & strFile) Then 89 .WinButton("OK").Click Window("Flight Reservation").Set s(0) Dialog("Login").AtEndOfStream strCharacters = objFile.txt".1) myfile.Close Wend 12) Writing data to a text file Dim Stuff. WriteStuff.OpenTextFile("E:\Pavan. 1) Do Until objFile.txt". True) WriteStuff.txt".WriteLine(Stuff) WriteStuff.Close SET WriteStuff = NOTHING SET myFSO = NOTHING 13) Delete a text file Set objFSO=createobject("Scripting.filesystemobject") Set myfile= fso.OpenTextFile("e:\Pavan.") SystemUtil.Activate Dialog("Login").WinEdit("Password:"). ".
Set objFile = objFSO. File1.Pattern = sString oRegEx.GetFile(FilePath2).GetFile(FilePath1).FileSystemObject") Set oTxtFile = oFso.Size <> FS. 0) CompareFiles = False Do While File1.txt" sString="pavan" Const FOR_READING = 1 Dim oFso.OpenAsTextStream(1.GetFile(FilePath2).Read CompareFiles = StrComp(Str1.txt" f2="e:\Pavan2.Close() End Function Call Comparefiles(f1.OpenTextFile(sFileName.Close() File2. 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1. FilePath2) Dim FS.Getfile(strDirectory & strFile) objFile. oRegEx." End If 16) Counting the number of times a word appears in a file sFileName="E:\gcr.delete () End if 15) Comparing two text files Dim f1.ReadAll Set oRegEx = New RegExp oRegEx.Execute(sReadTxt) MatchesFound = oMatches.Size Then CompareFiles = True Exit Function End If Set File1 = FS. 0) Set File2 = FS. f2) = False Then MsgBox "Files are identical.OpenAsTextStream(1.txt" Public Function CompareFiles (FilePath1. oTxtFile.AtEndOfStream = False Str1 = File1. sReadTxt.GetFile(FilePath1).Global = True Set oMatches = oRegEx.f2) If CompareFiles(f1." Else MsgBox "Files are different. File2 Set FS = CreateObject("Scripting.Read Str2 = File2. oMatches Set oFso = CreateObject("Scripting.FileSystemObject") If FS. Str2. FOR_READING) sReadTxt = oTxtFile. f2 f1="e:\Pavan1.Count 90 .IgnoreCase = bIgnoreCase oRegEx.
EOF Wscript.FMT=Delimited""" objRecordset.Echo "Service: " & arrServiceList(i) Next Loop 91 .MoveNext Loop 18) Read a Text File into an Array Const ForReading = 1 Set objFSO = CreateObject("Scripting.OpenTextFile _ ("e:\pavan.csv".4.0.Open "SELECT * FROM PhoneList.Echo "Server name: " & arrServiceList(0) For i = 1 to Ubound(arrServiceList) Wscript.") Wscript. ". _ objConnection.Jet.Echo "Department: " & _ objRecordset.Recordset") strPathtoTextFile = "C:\Databases\" objConnection." & _ "Extended Properties=""text. ForReading) Do Until objTextFile.FileSystemObject") Set objTextFile = objFSO.AtEndOfStream strNextLine = objTextFile.OLEDB." & _ "Data Source=" & strPathtoTextFile & ".Echo "Extension: " & objRecordset.Fields.Fields.Open "Provider=Microsoft.Item("Extension") objRecordset.Fields.Item("Name") Wscript. adLockOptimistic.Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound 17) Read a CSV File Using Database Techniques On Error Resume Next Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Set objConnection = CreateObject("ADODB.Item("Department") Wscript. adOpenStatic. adCmdText Do Until objRecordset.Echo "Name: " & objRecordset.txt".Readline arrServiceList = Split(strNextLine .HDR=YES.Connection") Set objRecordSet = CreateObject("ADODB.
add objexcel.Workbooks."B") 8) SystemUtil.WinEdit("Password:").Application") 2) Set myFile=myExcel.WinEdit("Password:").Value Then msgbox "value is different" Else msgbox "value is same" End If Next objWorkbook1.Set Agent 11) Dialog("Login").close objWorkbook2.exe".Value = "Testing" objexcel.Value <> objWorksheet2.SetSecure pwd 12) Dialog("Login").cells(i.Cells(1.Application") objExcel.WinEdit("Agent Name:").Workbooks.xls") objexcel.Quit 2) Data Driven Testing through an External Excel Sheet 1) Set myExcel=Createobject("Excel."open" 9) Dialog("Login").Address).open ("C:\Documents and Settings\admin\My Documents\pavan.worksheets("Sheet1") 4) Rows_Count=mySheet.Visible = True Set objWorkbook1= objExcel."C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\".SaveAs("f:\exceltest.Activate 10) Dialog("Login")."".xls") Set objWorksheet1= objWorkbook1.count 5) For i= 1 to Rows_Count 6) Agent=mySheet.Open("E:\pavan2.UsedRange If cell.Excel File Operations 1) Create an Excel file.workbooks."A") 7) pwd=mySheet.Worksheets(1) For Each cell In objWorksheet1.Open("E:\pavan1.xls") 3) Set mySheet=myFile.application") objexcel.close 92 .Cells(i.Worksheets(1) Set objWorksheet2= objWorkbook2. 1).rows.xls") Set objWorkbook2= objExcel.Visible = True objexcel. enter some data and save the file through VB scripting? 1) 2) 3) 4) 5) 6) 7) Dim objexcel Set objExcel = createobject("Excel.Type micReturn 13) Window("Flight Reservation").Close 14) Next 3) Compare two excel files Set objExcel = CreateObject("Excel.Workbooks.ActiveWorkbook.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.usedrange.Range(cell.
Value ("res".xls") 6) Read an Excel Spreadsheet Set objExcel = CreateObject("Excel.Set datatable("pwd".exe" Dialog("Login").3) Dialog("Login").WinEdit("Password:").Workbooks.3) Dialog("Login").Click Window("Flight Reservation").VbEdit("val1").xls".xls".ImportSheet "C:\Documents and Settings\Administrator\Desktop\pavan.Click eres= Datatable.1.Workbooks.Activate VbWindow("Form1").ImportSheet "C:\Documents and Settings\Administrator\Desktop\pavan.Open("C:\Scripts\pavan.VbEdit("val2").objExcel.3)=fail End If Next 5) Open an Excel Spreadsheet Set objExcel = CreateObject("Excel.SetCurrentRow(i) VbWindow("Form1").VbEdit("res").Activate Dialog("Login").GetSheet (3).GetRowCount For i= 1 to n Datatable.Close Next Example 2): Datatable.3) VbWindow("Form1").GetSheet (3).Set datatable("agent".3 n=datatable.AddSheet "pavan" Datatable.Application") Set objWorkbook = objExcel.Application") Set objWorkbook = objExcel.WinButton("OK").3)=pass else datatable("res".SetCurrentRow(i) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.Set datatable("V1".Open _ 93 .Set datatable("V2".GetRowCount For i= 1 to n Datatable.3 n=datatable.quit set objExcel=nothing 4) Data Driven Testing using Data Table methods Datatable.AddSheet "pavan" Datatable.VbButton("ADD").GetROProperty ("text") If eres=ares Then datatable("res".1.3) ares=VbWindow("Form1").WinEdit("Agent Name:").3) VbWindow("Form1").
1).Cells(intRow.Font.Cells(1. 1).Size = 24 objExcel.Open("C:\Scripts\Sort_test.Visible = True objExcel.Application") objExcel.xlAscending.Echo "LastName: " & objExcel.Value Wscript. 1).Font.Range("A1") Set objRange3 = objExcel.Value Wscript.ColorIndex = 3 8) Sort an Excel Spreadsheet on Three Different Columns Const xlAscending = 1 Const xlDescending = 2 Const xlYes = 1 Set objExcel = CreateObject("Excel.xlDescending.Echo "CN: " & objExcel. 1).Echo "sAMAccountName: " & objExcel.Application") objExcel.Cells(1.Cells(intRow.Cells(1.Value = "" Wscript.Bold = TRUE objExcel.Visible = True Set objWorkbook = _ objExcel.Range("C1") objRange.xls") intRow = 2 Do Until objExcel.Add objExcel.objRange3..Visible = True Set objExcel = CreateObject("Excel.Quit 7) Add Formatted Data to a Spreadsheet Set objExcel = CreateObject("Excel. 3).1).xlDescending. 1).xls") Set objWorksheet = objWorkbook.Cells(intRow.("C:\Scripts\New_users.Application") objExcel.Cells(intRow.Cells(intRow. _ objRange4.Cells(1. 2).Workbooks.Value intRow = intRow + 1 Loop objExcel.Echo "GivenName: " & objExcel.UsedRange Set objRange2 = objExcel.xlYes 94 .Value Wscript.Worksheets(1) Set objRange = objWorksheet. 4).Font.Workbooks.Range("B1") Set objRange4 = objExcel.Sort objRange2.Value = "Test value" objExcel.
Activate 10) Dialog("Login").WinButton("OK").exe" 9) Dialog("Login").Set rs. Some of the methods and properties of this object are not available depending on the type of data source connected to. Using ADO is quite simple and allows programmers to provide flexible database front ends to users that are reliable and include many features.oledb.0") 5) con.eof <>True 8) SystemUtil.WinEdit("Agent Name:").Set rs.Path) or can be across a network in a client server application.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a. RecordSet Object The RecordSet object represents a complete set of records from an executed command or from an underlying base table in the database.movenext 15) Wend 95 .fields ("Agent") 11) Dialog("Login"). Following are some of the key objects found in the ADO object model and some of their key methods and properties.jet.open "C:\Documents and Settings\Administrator\My Documents\Pavan.4.open "Select * From Login".connection") 3) Set rs=createobject("Adodb. this technology allows users to access data easily from many existing databases (such as Access or Paradox) or from ODBC compliant databases like Oracle or MS SQL Server.Close 14) rs.con 7) While rs. This connection can be a local connection (say App.rs 2) Set con=createobject("Adodb.Click 13) Window("Flight Reservation").mdb" 6) rs. Examples 1) Get Test Data from a Database and use in Data Driven Testing (through Scripting) 1) Dim con.fields ("Password") 12) Dialog("Login"). A key thing to note is that a RecordSet object references only one record at a time as the current record.WinEdit("Password:"). Command Object A command object specifies a specific method we intend to execute on or against the data source accessed by an open connection.provider=("microsoft. Connection Object This object represents an open connection to the data source.recordset") 4) con.Database Operations ADO (Active Data Objects).
cells(i.open"select*from Login".mdb" 6) rs.open"C:\Documents and Settings\gcr\My Documents\pavan.save 18) a.cells (i.Connection") Set objRecordSet = CreateObject("ADODB.workbooks.txt".Recordset") set objFso=createobject("Scripting.Fields ("Agent") b=objRs.jet.con 7) Set ex=createobject("Excel.Writeline a &".open "select * from login".4.open"C:\Documents and Settings\admin\My Documents\Pavan.1).connection") Set objRs=createobject("Adodb.rs 2) Set con=createobject("adodb.worksheets("sheet1") 10) i=1 11) Do While Not rs.provider="microsoft.EOF a=objRs.close 3) Exporting Data from a Database to a Text file Dim objCon.value=rs.Filesystemobject") Set myFile=objFso.connection") 3) Set rs=createobject("adodb.objRs.oledb.open("C:\Documents and Settings\admin\My Documents\Pavan.0" 5) con.0") objcon.myData.Recordset") 96 .EOF 12) b.r Set objCon=createobject("Adodb."& b r=r+1 objRs.fields("password") 14) rs.Fields ("Pwd") myFile.Close objCon.recordset") 4) con.ObjFso.value=rs.rc.provider=("Microsoft.xls") 9) Set b=a.objCon r=1 Do until objRs.4.mdb" objrs.MoveNext Loop myFile.Close 4) Connecting to a SQL Sever database Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.myFile.2).movenext 15) i=i+1 16) Loop 17) a.8) objcon.2) Exporting Data from a Database to an Excel Sheet 1) Dim con.Application") 8) Set a=ex.OpenTextFile("C:\Documents and Settings\gcr\My Documents\pavan.oledb.fields("agent") 13) b.jet.
adLockOptimistic objRecordSet.Recordset") objConnection. adLockOptimistic objRecordSet.Open "SELECT * FROM Customers".objConnection.4.Open _ "Northwind. adOpenStatic.Initial Catalog=Northwind.Recordset") Set objRecordSet2 = CreateObject("ADODB.Echo objRecordSet.Recordset") objConnection. adLockOptimistic objRecordSet.RecordCount 6) Open Two Record sets Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.34ghfn&!j" objRecordSet.Open _ "Provider= Microsoft.Connection") Set objRecordSet = CreateObject("ADODB. adOpenStatic. _ objConnection.fabrikam\kenmyer.OLEDB.mdb" objRecordSet. _ objConnection.RecordCount 5) Open a Database Using a DSN Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Open _ "Provider=SQLOLEDB.Open "SELECT * FROM Customers".Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'".Jet." & _ "User ID=fabrikam\kenmyer." objRecordSet.MoveFirst 97 . " & _ "Data Source=inventory. adOpenStatic.Data Source=atl-sql-01.Connection") Set objRecordSet = CreateObject("ADODB.MoveFirst Wscript.MoveFirst Wscript.Echo objRecordSet." & _ "Trusted_Connection=Yes.Password=34DE6t4G!.0. _ objConnection.
Echo "Number of records: " & objRecordset.mdb" objRecordSet.0.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'".EOF Wscript.Close 8) Insert Data into a database table using Database Command Object Dim objCon.EOF Wscript.Jet.Fields.Fields.MoveFirst Do Until objRecordset.Item("OSName") objRecordSet.Jet.MoveFirst Wscript.Close objConnection. adLockOptimistic objRecordSet2.0.connection") objCon.Open _ "Provider = Microsoft.Echo objRecordset." 98 .open"Provider=Microsoft.RecordCount objRecordSet.Open "SELECT * FROM EventTable " & _ "WHERE Type = 'Error'". adOpenStatic.Close objRecordSet2. " & _ "Data Source = eventlogs.Echo objRecordset2.Close objConnection.Echo objRecordset.4.OLEDB.objRecordSet2.MoveNext Loop Do Until objRecordset2.Item("ComputerName") Wscript. adOpenStatic.Close 7) Searching a Database Using String Criteria Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB. _ objConnection.Fields.Fields. objConnection.Recordset") objConnection.Connection") Set objRecordSet = CreateObject("ADODB.Data Source=C:\pavan.4.OLEDB. _ objRecordset2.Item("DriveDescription") objRecordSet2.mdb.objCom Set objCon=Createobject("ADODB.MoveNext Loop objRecordSet. _ adLockOptimistic objRecordSet.Item("DriveName").
ActiveConnection=objCon objCom.strEmpName.intEmpSal.CommandText="insert into Emp values( '"&strEmpName&" '.ActiveConnection=objCon Datatable."&intEmpSal&")" objCom.Command") objCom.Data Source=C:\pavan.intEmpNo.ImportSheet "C:\pavan.mdb.Value(3.open"Provider=Microsoft."input" intRowcount=Datatable.OLEDB."input") intEmpNo= DataTable.Execute Next objCon.GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.Jet.xls".Close Set objCom=Nothing Set objCon=Nothing 9) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon.Value(2." Set objCom=Createobject("ADODB.30000)" objCom.Execute objCon.Set objCom=Createobject("ADODB.intRowcount."&intEmpNo&".AddSheet("input") Datatable.GetSheet("input")."input") objCom.4.connection") objCon.1.0.SetCurrentRow(i) strEmpName= DataTable.Close Set objCom=Nothing Set objCon=Nothing Object Identification Configuration 99 .i Set objCon=Createobject("ADODB.objCom.88233.Command") objCom.Value(1.CommandText="insert into Emp values('G C Reddy'."input") intEmpSal= DataTable.
first qtp learns all base filter properties at a time and thinks whether these properties are sufficient for identifying the object uniquely. It learns first assistive property and once again stops and thinks. if it feels sufficient then it stops learning otherwise. and then we configure Smart Identification for that object. qtp recognizes object using 2 0r 3 important properties. At the end of assistive properties list also if it feels not satisfied and it finally goes to Ordinal Identifier. Ordinal identifiers: 10 . Qtp has default object identification configuration for every environment. then it stops learning otherwise it goes Optional Filter Properties and learns one by one. QTP learns information in the following in case of Smart Identification: Smart identification is an optional feature. in order to avoid Ordinal Identifier. If it feels sufficient. After normal identification if qtp feels not satisfied then it goes to smart identification.Overview: Generally for every object 20-25 properties information available. we can configure some more Object Identification Types a) 1) 2) b) 1) 2) c) Normal identification Mandatory properties Assistive properties Smart identification base filter properties optional filter properties Ordinal identifier 1) 2) 3) location index creation time(only for web) QTP learns information in the following in case of normal identification: First of all the qtp learns all the mandatory properties at a time and thinks whether these properties sufficient to identify the object uniquely. in smart identification 2 types of properties available. Still it feels not satisfied finally it goes to Ordinal Identifier. like this qtp learns one by one. if we feel that configuration is not sufficient for recognizing objects in our application. if we feel normal identification is not sufficient for any object.
location starts from zero. qtp generates 0.1. index starts from zero 3) Creation time: it is based on loading time of the web objects. 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. Regular Expressions in QTP 10 . STEPS: 1) Settings available in 3 areas. QTP is providing a special feature called "Generate Script". 2) index: it is based on sequence of the programs. NOTE: After executing these scripts all team members can get same settings. For making tool settings global.2 like numbers. Tool Settings Globalization: As QTP is a I-tier(Stand-alone) application.making Tool settings globally is not possible.There are 3 types of ordinal identifiers available 1) Location: is based on object location in the AUT .
What is Regular Expression? It is a way of representing data using symbols. We can define the text string as a regular expression. w. We can define a regular expression in standard checkpoint to verify the property values of an object. Alternatively. when creating a text checkpoint to check that a varying text string is displayed on our application. if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values. or d. Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value. such as the letters n. They are often used within matching. For XML checkpoints we can set attribute or element values as regular expressions. the combination indicates a special character. an Environment parameter value. a Data Table parameter value. 10 . It can be used in conjunction with a special character to indicate that the next character be treated as a literal character.) instructs QTP to search for any single character (except for \n). or a property value in Descriptive programming. searching or replacing algorithms. we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified. t. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. b) Matching Any Single Character: A period (.
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, az, 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
OpenTextFile(strFileName) strFileContents = objTS.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Value -------------------------------------------------- Batch Testing Executing a group of tests/series of tests at a time is known as Batch Testing or 10 .Arguments(0) Set colMatches = objRE.Regular Expressions Examples: 1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.Close Set objRE = New RegExp objRE.CurrentDirectory Set objFolder = objFS.IgnoreCase = False objRE.Echo "At position " & objMatch.Pattern = WScript.Echo "Searching Within: " WScript.FirstIndex & " matched " & objMatch.Echo strFileContents objTS.Files Set objRE = New RegExp objRE.Execute(strFileContents) WScript.Shell") strCurrentDirectory = objShell.Global = True objRE.FileSystemObject") Set objTS = objFS.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\pavan.ReadAll WScript.Echo objFile.Arguments(0) For Each objFile In colFiles bMatch = objRE.txt" Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Pattern = WScript.Global = True objRE.Name) If bMatch Then WScript.Test(objFile.IgnoreCase = False objRE.GetFolder(strCurrentDirectory) Set colFiles = objFolder.
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. Note: Allowing other products to Run Tests. Steps for Batch Testing: 1). Create Individual Tests and Run once. 2). 5) View Test wise Result in 'Test Result Viewer' Forming a Test Batch: Launch Test Batch Runner. QTP has provided a separate Tool called 'Test Batch Runner'. 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. 3) Provide permission to 'Test batch Runner' to run tests 4). For performing Batch Testing. Run or Execute Test Batches from Test Batch Runner. Open 'Test batch Runner' Tool and Form Batches. VB Script Other Objects 10 . QTP runs Tests one by one. 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.Batch Execution.
1) Dictionary Object Dictionary Object that stores data key. Items can be any form of data. but can be anything except an array. "Chennai" Dictionary Objects Properties: Count Property 10 . and are stored in the array. false if it does not.Add "h". Remove Method Removes a key. item pair from a Dictionary object. RemoveAll Method The RemoveAll method removes all key. The key is used to retrieve an individual item and is usually an integer or a string. "Bangalore" cities.Add "b". Keys Method Returns an array containing all existing keys in a Dictionary object. Creating a Dictionary Object: Set objDictionary = CreateObject("Scripting. Example: Dim cities Set cities = CreateObject("Scripting. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items Method Returns an array containing all the items in a Dictionary object.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. "Hyderabad" cities. item pairs.Dictionary") cities. item pairs from a Dictionary object.Add "c". Each item is associated with a unique key.
Key Property Sets a key in a Dictionary object.Add "Printer 2".Dictionary") objDictionary.Echo "First run: " For Each strKey in colKeys Wscript.Add "Printer 2". Read/write.Echo strKey Next objDictionary.Add "Printer 1". "Offline" objDictionary.Echo strKey Next 10 .Returns the number of items in a collection or Dictionary object. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object. "Offline" objDictionary. "Printing" objDictionary.RemoveAll colKeys = objDictionary.Add "Printer 1". "Printing" objDictionary.Add "Printer 3".Keys Wscript. Read-only.Keys Wscript. "Printing" 2) Delete All Elements from Dictionary Set objDictionary = CreateObject("Scripting.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript. For collections.Dictionary") objDictionary. Item Property Sets or returns an item for a specified key in a Dictionary object. "Printing" colKeys = objDictionary. returns an item based on the specified key.Add "Printer 3". Examples: 1) Add Elements to a Dictionary Set objDictionary = CreateObject("Scripting.
"Printing" colKeys = objDictionary.3) Delete One Element from a Dictionary Set objDictionary = CreateObject("Scripting.Keys Wscript.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript. "Printing" objDictionary.Add "Printer 2".Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Dictionary") 11 . "Offline" objDictionary.Dictionary") objDictionary.Add "Printer 3".Echo strKey Next objDictionary.Remove("Printer 2") colKeys = objDictionary.Echo strKey Next 4) List the Number of Items in a Dictionary Set objDictionary = CreateObject("Scripting.Add "Printer 1".
"Printing" objDictionary.Add "Printer 1".Add "Printer 2".Add "Printer 3".objDictionary. "Printing" Wscript.Add "Printer 1".Exists("Printer 4") Then Wscript." Else Wscript.Add "Printer 3".Count 5) Verify the Existence of a Dictionary Key Set objDictionary = CreateObject("Scripting. "Offline" objDictionary.Echo "Printer 4 is not in the Dictionary.Dictionary") objDictionary. It provides simple support for defining regular expressions.Echo objDictionary.Echo "Printer 4 is in the Dictionary. "Printing" objDictionary. "Offline" objDictionary." End If 2) RegExp object VB Script is providing RegExp object 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 11 .Add "Printer 2". "Printing" If objDictionary.
Files Set objRE = New RegExp objRE.Test(objFile.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\pavan.CurrentDirectory Set objFolder = objFS.FileSystemObject") 11 .Shell") strCurrentDirectory = objShell.txt" Set objFS = CreateObject("Scripting.1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Echo objFile.Pattern = WScript.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Arguments(0) For Each objFile In colFiles bMatch = objRE.IgnoreCase = False objRE.Global = True objRE.Name) If bMatch Then WScript.
IgnoreCase = False objRE.Echo "Searching Within: " WScript.30000)" objCom.FirstIndex & " matched " & objMatch.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.objCom Set objCon=Createobject("ADODB.CommandText="insert into Emp values('G C Reddy'.4.Global = True objRE.Data Source=C:\pavan.mdb.connection") objCon.Close 11 .Command") objCom.Jet.0.open"Provider=Microsoft.Arguments(0) Set colMatches = objRE.88233.Set objTS = objFS.Execute objCon.Echo "At position " & objMatch." Set objCom=Createobject("ADODB.Execute(strFileContents) WScript.Pattern = WScript.OpenTextFile(strFileName) strFileContents = objTS.Value Next 3) Database Command Object 1) Insert Data into a database table using Database Command Object Dim objCon.Echo strFileContents objTS.OLEDB.Close Set objRE = New RegExp objRE.ActiveConnection=objCon objCom.ReadAll WScript.
ActiveConnection=objCon Datatable.AddSheet("input") Datatable.quit set mw=nothing 2) Create Script to get the list of links in Google and do spell check Dim d set mw=CreateObject("Word.Application") mw.Jet."input" intRowcount=Datatable.Documents.OLEDB.GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.4.SaveAs "e:\pavan.GetSheet("input").Value(3.intEmpSal.Command") objCom.Value(1.Value(2.i Set objCon=Createobject("ADODB.strEmpName.ImportSheet "C:\pavan.selection.intEmpNo.xls"."&intEmpSal&")" objCom.typetext "hello" mw."&intEmpNo&".0."input") intEmpSal= DataTable." Set objCom=Createobject("ADODB.intRowcount.CommandText="insert into Emp values( '"&strEmpName&" '.connection") objCon.1.Add mw.doc" mw."input") objCom.Set objCom=Nothing Set objCon=Nothing 2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon.Execute Next objCon.objCom.ActiveDocument.SetCurrentRow(i) strEmpName= DataTable.mdb.Data Source=C:\pavan.Application") 11 .Close Set objCom=Nothing Set objCon=Nothing 4) Word Object 1) Create a word document and write some data dim mw set mw=CreateObject("Word."input") intEmpNo= DataTable.open"Provider=Microsoft.
ReportEvent 1.childobjects(d) for i=0 to a.Name&" "&f.value="Link" set a=Browser("Google")."spelling error :"&s end if mw.Drives mw.LookIn=dr mw.FileSearch.FileSearch.Execute For each i in mw.FileSystemObject") Set d=fs.filenew s=a(i).WordBasic.getROProperty("innertext") mw.ActiveDocument.Quit 11 .FoundFiles print i Set f=fs.FileSearch.FileSearch."Spelling".page("Google").doc" For each dr in d msgbox dr mw.Close(False) next mw.Spellingerrors.FileName="*.count>0 then Reporter.Size&" "&f.SearchSubFolders=True mw.insert s if mw.DateCreated print "-------------------------------------------------------------------" Next Next mw.Application") Set fs=createobject("Scripting.quit set mw=nothing 3) Script to display all the doc files in all the drives in the system Dim mw Set mw=CreateObject("Word.FileSearch.set d=Description.GetFile(i) print f.Create d("micclass").count-1 mw.ActiveDocument.WordBasic.
Or A systematic approach to automate software Test process Why Automation Framework: In one project test automation we use various files.xls) c) Object repository files (. efficient and optimized way.5) IE Object 1) Open Internet Explorer and navigate to yahoo mail Dim ie Set ie=CreateObject("InternetExplorer.GetROProperty("title") msgbox x Automation Framework Automation: Accessing one Software Objects from another Software is called Automation.txt). in order to organize and manage them all. b) Excel files (.xml) 11 . we perform various tasks.yahoomail. assumptions and process developed by experts in order to perform a task(s) in an effective.) Automation Framework: It is a set of guidelines.Navigate "www. Files to be used: a) Flat files (. (AUT is one s/w and Testing Tool is another s/w. a systematic approach (Automation Framework) required.com" x=Browser("CreationTime:=0").tsr) d) XML files (.Visible=True ie.Application") ie.
m) Modifying tests n) Performing re and regression testing ---etc Types Of Automation Framework: Automation Framework is not a qtp feature. Record/Playback or Linear Framework (1st generation framework). And this is purely local concept.qfl) f) Test Scripts (. Form Etc.e) Library files (.(framework may vary from one company to another) 1.qrs) i) Test Result file (. Test Batch execution --etc) i) Defining and exporting test results j) Analyzing results k) Test reporting l) Defect Reporting using companies defect management system.low resources maintenance. Schedule. Transaction points.mts) g) Test Batch Files (. Environment variable files---etc) f) Creating Tests (Using Object Repository or Descriptive Programming) g) Enhancing Tests(Inserting Checkpoints. In this Framework we create tests using recording. Flow Control Statements. 11 .vbs/.mtb) h) Recovery scenario files (. it's a 3rd party concept. e) Creating required Automation resources (Functions. Synchronization. Parameterization---etc ) h) Debugging and running tests(Individual test execution.. Object repository Files. Output Values.. Work allocation and Automation Framework implementation) d) Creating Generic and project specific functions.XML) Tasks to be performed: a) Analyzing the application b) Selecting Areas/Test Cases for Automation c) Planning (Effort estimation.
low in performance.Flexible for performing any tasks. 3. 11 . Drawbacks: Organizing and managing resources are difficult.batches and executing tests. It is a mixing of more than one approach. Advantages: It reduces test Automation time Performance is high than recording and playback Drawbacks: Less usage of keywords. Hybrid Framework In the above frameworks Keyword Driven framework is very famous in the industry.then collecting test data and parameterizing. In this Framework.low performance ---etc 2. Advantages: We can check reliability of the system. In this approach.We recognize positive and negative scenarios.we mix Data driven and Modular approaches OR Data Driven and Keyword Driven approaches---etc Advantages: Scope is very high as we mix different approaches.positive and negative testing. 4.we concentrate more on Data Driven testing. Data Driven Framework In this Framework. no concentration on Data driven testing and low performance than latest Frameworks like Keyword Driven Framework.less command on scripts. Drawbacks: Less concentration on complex Functionality Testing and low keywords usage.complex architecture. then creating tests using those components. Keyword Driven framework 5.first we concentrate on creating reusable components.reusable components can be recognized. Modular Framework. Drawbacks: Modifications and maintenance are difficult.
through framework we execute them and generate results.*. Folder Structure: 1. Object Repository 2. 2. Library 11 . store.or. Keyword Driven Framework Keyword: 1. Environment 3. 5. Any word used as the key to a code 2 A reserved word used to identify a specific command.Navigate---etc) d) Statements (EX:Dim./. (in our test automation example keywords are : Keywords to be used in Test Automation: a) Test Objects (EX: Browser.For---etc) e) Operators (EX: +.If.not---etc) Keyword Driven Approach: In this approach we use keywords for preparing tests. but folder names may vary from one framework to another and company to another . 3.WinButton---etc) b) Functions (Built-In and User defined) c) Methods (Ex:Set. 4.NOTE: Now a days Mix of Data driven and Keyword driven approaches is a famous Hybrid Framework in the industry. Key elements of Automation Framework: 1. Folder structure is a mandatory element of any framework.page. Well defined folder structure Initialization script Driver script input data spreadsheet process guidelines document Why folder structure? In order to create.Activate.webEdit. organize and manage files a well defined folder structure required.Select. function etc.and. First we create tests and make them as functions.
mdb files. we can associate all resources to this script QTP Add-Ins Information Standard Windows Environment Object Desktop Description An object that enables you to access top-level 12 . 4) Test Data: in this folder we store test data required for data driven testing. for that we use either .qrs).vbs file): It launches qtp tool and calls driver script.tsr). at end it closes qtp tool. 3) Function Library:this folder contains two sub folders one is for storing common functions of our company. all team members can use this variables.vbs file) 2. another folder for storing our project specific functions(. Test log 6.vbs). Miscellaneous And 1. Test data 5.xls files or . Initialization script (.txt files or .xml). Recovery scenarios 7. 7) Miscellaneous: in this folder we store the files other than above files(ex-process guideline doc and messages among team members and instructions by team lead etc). Driver script (QTP Script file) 1) Object Repository: In this folder we store object repository files(. 6) Recovery scenarios: In this folder we store qtp recovery scenarios files(. all team members can use this repositories. 2) Driver script (QTP Script file): It is only the qtp script. 2) Environment: In this folder we store environment variables files(. And 1) Initialization script (.a) Company b) Project Specific 4. 5) Test Log: In this folder we store test result(excel sheet).
Stingray tree control. A Windows status bar. An image with or without a target URL link. A Windows combo box. A Windows calendar. 12 . A Windows dialog box. A Windows edit box. An object used to control applications and processes during a run session. A Windows button. Windows toolbar. A Windows spin box. A Windows list. A Windows radio button. A Windows menu. An HTML frame. A Windows tree-view control. Web Environment Object Browser Frame Image Description A Web browser (or browser tab). A Windows multi-line editor. A Windows list-view control. A standard window.Dialog Static SystemUtil WinButton WinCalendar WinCheckBox WinComboBox Window WinEdit WinEditor WinList WinListView WinMenu WinObject WinRadioButton WinScrollBar WinSpin WinStatusBar WinTab WinToolbar WinTreeView items on your desktop. A static text object. A standard (Windows) object. A Windows toolbar. A Windows tab strip in a dialog box. Stingray grid. A Windows scroll bar. Stingray Environment Object WinTab WinTable WinToolbar WinTreeView A A A A Description Windows tab strip in a dialog box. A Windows check box.
An HTML button. A section of an image (usually a section of a client-side image map). A test object representing a Web service. A general Web object that can represent any Web object. An edit box with a browse button attached. A utility object used to check WSDL files. An object that supports header-related test object operations. VBScript Glossary ActiveX control 12 . A set of radio buttons belonging to the same group. A Viewlink object. An HTML page. A check box with an ON and OFF state. used to select a file from the File dialog box. A table containing a variable number of rows and columns. An object that supports security-related test object operations. An object that supports configuration-related test object operations. An XML document contained in a Web page. usually contained inside a form. A drop-down box or multiple selection list. An edit box.Link Page ViewLink WebArea WebButton WebCheckBox WebEdit WebElement WebFile WebList WebRadioGroup WebTable WebXML A hypertext link. Web Services Environment Object Attachments Configuration headers Security WebService WSUtil Description An object that supports attachment-related test object operations.
rather than the value. Each element of an array has a unique identifying index number. ActiveX object An object that is exposed to other applications or programming tools through Automation interfaces. or expression passed to a procedure. Changes made to one element of an array do not affect the other elements. variable. By value A way of passing the value. keyboard. By reference A way of passing the address. ASCII Character Set American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U. Automation object An object that is exposed to other applications or programming tools through Automation interfaces. of an argument to a procedure. the variable's actual value can be changed by the procedure to which it is passed.An object that you place on a form to enable or enhance a user's interaction with an application. rather than the address. Bitwise comparison A bit-by-bit comparison of identically positioned bits in two numeric expressions. the variable's actual value can't be changed by the procedure to which it is passed. Argument A constant.S. Boolean expression An expression that evaluates to either True or False. The controls have an . As a result. ActiveX controls have events and can be incorporated into other controls. The ASCII character set is the same as the first 128 characters (0– 127) in the ANSI character set. This allows the procedure to access a copy of the variable. Array A set of sequentially indexed elements having the same type of data. As a result. 12 . This allows the procedure to access the actual variable.ocx file name extension. of an argument to a procedure.
character code A number that represents a particular character in a set, such as the ASCII character set. Class The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior. Class module A module containing the definition of a class (its property and method definitions). Collection An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary. Comment Text added to code by a programmer that explains how the code works. In Visual Basic Scripting Edition, a comment line generally starts with an apostrophe ('), or you can use the keyword Rem followed by a space. Comparison operator A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (=). Is is also a comparison operator, but it is used exclusively for determining if one object reference is the same as another.
Constant A named item that retains a constant value throughout the execution of a program. Constants can be used anywhere in your code in place of actual values. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. For example: Const A = "MyString" Data ranges Each Variant subtype has a specific range of allowed values:
Sub Range typ e Byt e 0 to 255.
Boo True or False. lea n Int -32,768 to 32,767. ege r Lon -2,147,483,648 to 2,147,483,647. g Sin gle Do ubl e Cur ren cy -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Dat January 1, 100 to December 31, 9999, inclusive. e Obj Any Object reference. ect Stri Variable-length strings may range in length from 0 to ng approximately 2 billion characters.
Date expression Any expression that can be interpreted as a date. This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999. Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899.
Date literal Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale
settings for your code or the universal date format. For example, #12/31/99# is the date literal that represents December 31, 1999, where English-U.S. is the locale setting for your application. In VBScript, the only recognized format is US-ENGLISH, regardless of the actual locale of the user. That is, the interpreted format is mm/dd/yyyy.
Date separators Characters used to separate the day, month, and year when date values are formatted. Empty
A value that indicates that no beginning value has been assigned to a variable. Empty variables are 0 in a numeric context, or zero-length in a string context.
Error number A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the Err object. When combined with the Name property of the Err object, this number represents a particular error message. Expression A combination of keywords, operators, variables, and constants that yield a string, number, or object. An expression can perform a calculation, manipulate characters, or test data. Intrinsic constant A constant provided by an application. Because you can't disable intrinsic constants, you can't create a user-defined constant with the same name. Keyword A word or symbol recognized as part of the VBScript language; for example, a statement, function name, or operator. Locale
The set of information that corresponds to a given language and country. A locale affects the language of predefined programming terms and localespecific settings. There are two contexts where locale information is important: 2. The code locale affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.
File. Null is the result of: 3. when you display numbers or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system. The system locale affects the way locale-aware functionality behaves.3. Nothing The special value that indicates that an object variable is no longer associated with any actual object.1415926535897932. Elements of the expression can include any combination of keywords. Numeric expression Any expression that can be evaluated as a number. Private Variables that are visible only to the script in which they are declared. and Sheet. constants. For example. followed by assignments and other executable code. Procedure level Describes statements located within a Function or Sub procedure. for example. 4. for example. and operators that result in a number. Any operation between expressions that contain Null. Procedure A named sequence of statements executed as a unit. variables. Declarations are usually listed first. Application. Object type A type of object exposed by an application. Range. A = "My variable" ' Procedure-level code. pi Pi is a mathematical constant equal to approximately 3. Function and Sub are types of procedures. An explicit assignment of Null to a variable. Null A value indicating that a variable contains no valid data. 12 . Dim A ' This statement starts the procedure block. For example: Sub MySub() ' This statement declares a sub procedure block. Microsoft Project. Microsoft Word. Refer to the application's documentation (Microsoft Excel. and so on) for a complete listing of available objects.
or the state of an object. Unless specified in the function making the comparison. Scope Defines the visibility of a variable. Note that script-level code resides outside any procedure blocks. 12 . procedure. all string comparisons are binary. Run-time error An error that occurs when code is running. you can't edit the code. For example. such as enabled or disabled. End Sub ' This statement ends a sub procedure block. Properties define object characteristics such as size. The status codes for OLE interfaces and APIs are defined in FACILITY_ITF. Variables declared in procedures are visible only within the procedure and lose their value between calls. In English. Property A named attribute of an object.Debug. String comparison A comparison of two sequences of characters. binary comparisons are case-sensitive. A run-time error results when a statement attempts an invalid operation. the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.Print A ' Procedure-level code. For example. Run time The time when code is running. a variable declared as Public is visible to all procedures in all modules. color. Script level Any code outside a procedure is referred to as script-level code. Seed An initial value used to generate pseudorandom numbers. text comparisons are not. or object. Public Variables declared using the Public Statement are visible to all procedures in all modules in all applications. During run time. and screen location. SCODE A long integer value that is used to pass detailed information to the caller of an interface member or API function.
properties. • Must be unique within the same scope. • Can't contain an embedded period or type-declaration character. Variable names: • Must begin with an alphabetic character. Variable A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope. and methods. Type library A file or component within another file that contains standard descriptions of exposed objects. a string literal. a string constant. • Must be no longer than 255 characters.String expression Any expression that evaluates to a sequence of contiguous characters. or a string variable. Elements of a string expression can include a function that returns a string. 12 .
. Action can have a object repository associated with it while a function can't.number<> 0 then 'Parameter does not exist else 'Parameter exists end if 3) How can i check if a checkpoint passes or not? chk_PassFail = Browser(. a function like getting a string between to specific characters..WebEdit(. A function is just lines of code with some/none parameters and a single return value while an action can have more than one output parameters. 6) Where to use function or action? Well answer depends on the scenario. now this is something not specific to QTP and can be done 13 . Just append ' to the number Ex: if you wish to enter 1234567 in datatable then write it as '1234567 2) How can i check if a parameter exists in DataTable or not? The best way would be to use the below code: on error resume next val=DataTable("ParamName"..WebEdit(.).Check (Checkpoint("Check1")) Reporter.Some Useful Tips with QTP 1) How to add a constant number in a data table? This is more to do with MS excel then QTP!! but useful to know because at times it becomes frustrating to the novices..Page(.. If you want to use the OR feature then you have to go for Action only..Filter = rfDisableAll 'Disables all the reporting stuff chk_PassFail = Browser(..Check (Checkpoint("Check1")) if chk_PassFail then MsgBox "Check Point passed" else MsgBox "Check Point failed" end if 4) My test fails due to checkpoint failing..Filter = rfEnableAll 'Enable all the reporting stuff if chk_PassFail then MsgBox "Check Point passed" else MsgBox "Check Point failed" end if 5) What is the difference between an Action and a function? Action is a thing specific to QTP while functions are a generic thing which is a feature of VB Scripting..).dtGlobalSheet) if err....).e.). Can i validate a checkpoint without my test failing due to checpoint failure? Reporter.Page(. If the functionality is not about any automation script i.).).
and then retrieves the variable value and stores it in the MyValue variable. Use err. and comments regarding the files that make up a QuickTest Professional test. 7) When to use a Recovery Scenario and when to us on error resume next? Recovery scenarios are used when you cannot predict at what step the error can occur or when you know that error won't occur in your QTP script but could occur in the world outside QTP. Decision of using function/action depends on what any one would be comfortable using in a given situation. 8) How to use environment variable? A simple defintion could be. "On error resume next" should be used when you know if an error is expected and dont want to raise it.number & err.on pure VB Script.Value("MyVariable") 9) What are the files and subfolders of a QuickTest Professional test? The files and folders hold binary and text data that are required for the test to run successfully.Value("MyVariable")=10 MyValue=Environment. But we can set the value of only userdefined environment variables. again the example would be "out of paper". The following table provides a description. User-defined 2.mtr Action Default. There are two types of environment variables: 1. Built-in We can retrieve the value of any environment variable. as this error is caused by printer device driver. it is a variable which can be used across the reusable actions and is not limited to one reusable action.xls Parameters. Code specific to QTP can also be put into an function using DP.tsp Default. the type. Environment.. File Name Test.. To set the value of a user-defined environment variable: Environment (VariableName) = NewValue To retrieve the value of a loaded environment variable: CurrValue = Environment (VariableName) Example The following example creates a new internal user-defined variable named MyVariable with a value of 10. you may want to have different actions depending upon the error that occurred.description to get more details about the error.cfg Description Test settings Data table parameters Parameterization information Action folder (See other table) Load test configuration file Text Do not edit Type Binary Excel similar Binary Comments Regarding File Do not edit Can be edited using Excel Do not edit 13 . so this should be done in a function and not an action.
0 QuickTest Professional 9.0? QuickTest Professional 9.MTB Batch File . 4. you may need to recreate the checkpoint to resolve the error.usr Thick_usr.WinEditor("Edit").0 Beta 2. QuickTest Professional will generate an error during replay. Click .mts Resource. The name of the checkpoint object will be updated within the script. Internet Explorer version 7. the user would like to change the name of the CheckPoint object from "Edit" to something more meaningful. 1.2 and below. so if you manually modify the name.LCK Locked 10) How to rename a checkpoint (QTP 9.0 Beta 3. Check the Object Repository to confirm that the object exists or to find the correct name for the object. If you manually change the name of the checkpoint in the script. QuickTest Professional 9.1 supports Microsoft Internet Explorer 7.WinEditor("Edit").0 is now certified to work and to be tested with QuickTest Professional version 9.mtr Description Action script Object Repository Type Text Comments Regarding File Edit text preceding the @@ sign only Binary Do not edit Snapshots Active screen files Folder Do not edit There are few more files extensions like ." The CheckPoint object is not a visible object within the object repository. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object in Expert View.dat Load test configuration file Text Files within Action folder: File Name Script. The error message will be similar to the following: "The "" CheckPoint object was not found in the Object Repository. 3.This is not available for QTP 8. 13 .Default. Example: Window("Notepad").1.dat Load test configuration file Text Load test configuration file Text Load test configuration file Text Load test configuration file Text Do not edit Do not edit Do not edit Do not edit Do not edit Thin_usr. Select "Checkpoint Properties" from the pop-up menu. enter the new checkpoint name. 2. Note: This functionality is new to QuickTest Professional 9.prm Default.0 supports Internet Explorer 7.Check CheckPoint("NewCheckPointName") Note: You must use the QuickTest Professional user interface to change the name of the checkpoint.Check CheckPoint("Edit") In the above example.usp .0. In the Name field. 11) Does QuickTest Professional support Internet Explorer 7.0)? Example: Window("Notepad").1 QuickTest Professional 9.
ini.1 provides replay support for Mozilla Firefox 1.2 and below QuickTest Professional 8. 3. The . Save the mic.Object property for web objects is not supported in FireFox.0a3).0 will not record on FireFox. Go to \bin\mic. with no extension.5 and Mozilla Firefox 2.ini file and restart QuickTest Professional. Windows Media will not start. Close QuickTest Professional. it will continue to work normally after starting QuickTest Professional.Object property for web objects is not supported in FireFox.2 and below do not include support for Internet Explorer 7. QuickTest Professional 8.0.ini file.exe in the NoBBTApps section of mic. You can record a test on Microsoft Internet Explorer and run it on any other supported browser. An error log is being created.5.ini file 1. Notes: QuickTest Professional 9. 13 . Check that you have selected Allow other mercury products to run tests and components from Tools--> Options--> Run Tab. QuickTest Professional 9.2 QuickTest Professional 9. Include wmplayer.0 QuickTest Professional 9. Whenever a new license is created. You will need to restart the program. The .exe=rek 4. The lservrc file is a text file. Notes: QuickTest Professional 9. File Location: 1) For a Concurrent (Floating) license installation: "#server installation directory#\#language#" Example: C:\Program Files\XYZ Technologies\ABC Server\English\lservrc 2) For a Seat (Stand-alone) license installation: #AQT/QTP installation directory#\bin" Example: C:\Program Files\Mercury Interactive\QuickTest Professional\Bin\lservrc 14) What to do if you are not able to run QTP from quality center? This is for especially for newbies with QTP. You can record a test on Microsoft Internet Explorer and run it on any other supported browser.0 provides replay support for Mozilla FireFox 1. 13) What is the lservrc file in QTP? The lservrc file contains the license codes that have been installed The lservrc file contains the license codes that have been installed. 2. Example: [NoBBTApps] wmplayer. Does QuickTest Professional support Firefox? QuickTest Professional 9.2 and below do not have support for Firefox. the license code is automatically added to this file.2 and below QuickTest Professional 8.QuickTest Professional 8. It returns the error message "wmplayer.0 Alpha 3 (Alpha-level support for Bon Echo 2.1 and 9. such as FireFox." If you start Window's Media Player first. 12) Problem After Quick Test Professional is started. Solution: Include the Windows Media Player's executable in the NoBBTApps section of the mic. such as FireFox.1 will not record on FireFox.exe has generated errors and will be closed by Windows.
QTP is not expected to run on this OS.15) Does QuickTest Professional support Macintosh operating systems? No. 13 .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.