• Like
Qtp basics
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Published

qtp basics

qtp basics

Published in Software , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,218
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
36
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. http://www.qtpskills.com/p/qtp-chapter-iii.html QTP - Chapter I Introduction of Automation Testing: - Testing is the process of improving the quality of software. Ways to testing: - Manual testing Automation testing Manual Testing: - It is a process where we complete all the phases of STLC (software testing life cycle) by manual, is called as manual testing Draw backs of manual testing: - Time consuming More number of human resources are required Tiredness of the testers Human errors (Less accuracy) Simultaneous actions are almost impossible Automation Testing:- Automation testing is a process where we can test the application with the help of Automation Tool Benefits of Automation Tool:- Fast: - It runs the script faster than human beings. Reusable: - We can reuse the scripts in different regression testing. Cost reduction: - It reduces number of resources and hence less budget. Accuracy: - No tiredness and hence good accuracy results. Disadvantage of Automation Testing:- Proficiency is required to write automation test scripts. It is expensive to buy. In all areas automation testing is not possible. Difference between Manual and Automation Testing:- Manual Testing:- 1. Testing is implemented by manually 2. 2. It is the best suite for application which the numbe of test cycles are less 3. The test case development is less 4. The test case execution time is more 5. The test data needs to be provide by manually 6. The test reports can be generated by manually 7. Defects need track manually 8. Organization point: the cost of manual testing is more 9. The programming knowledge is optional Automation Testing:- 1. Testing is implemented by using tools
  • 2. 2. It is the best suite for application which number of test cases less 3. Test script development time more 4. Test script execution is time is less 5. The test data can be generated by tool it self 6. The test cases can be generated by automatically 7. Defects can be tracks automatically 8. the cost of automation testing is more 9. A minimum programming knowledge is required Types of testing can be done by Automation: - Functional (Positive and Negative) testing Regression Testing Performance Testing Usability Testing Functional Tools:- Quick Test Professional (QTP) IBM rational functional tester Winrunner Selenium Test complete Performance tools:- Load runner J meter Test complete Test Management Tools:- Test direct Quality center Bugzilla Rally Clear quest Things to done before Automation Testing: - 1. Return on investment (ROI) 2. Tool selection 3. Identify Framework 4. Automation feasibility Automation feasibility: - It is a process of identifying what test case can be automated and cannot be automated. This will be done by automation tester for their respective modules. What test case can be Automated: - The test case needs to be run on every build The test case needs to be run on multiple test data Multiple browser compatibility test cases Application objects which do not change in short time What test case cannot be Automated: - Security related test cases
  • 3. Idle time functionalities Batch processing requirements Graphs related test cases Usability test cases Documentation verification testing 3rd party objects requirements. Ex: - PDF, Printers etc... > After completion of Automation feasibility we go for estimations Example: - Finding number of resources to automate for 800 test cases in 100 days Number of test cases to designed per day = 800/100=8 test One resource 2 scripts per day How resources need if 8 scripts per day =8/2=4 resources Example: - Finding number of days to automate 800 test cases with 4 resources One resource 2 scripts/ day 4 resources 4*2=8 scripts/day Number of days = Total test cases/per day scripts= 800/8=100 days Automation testing process: - 1. ROI [Return on Investment] 2. Tool selection 3. Test cases feasibility analysis 4. Preparation of automation test plan document 5. Framework designing 6. Designing test scripts for manual test cases 7. Involve in code walkthroughs and code inspections 8. Test scripts debug 9. Involving in regression support by executing test scripts as a batch 10. User acceptance testing QTP Automation Chapter II Introduction to QTP (Quick Test Professional) Type of Tool: - it is a functional Regression Testing Tool Earlier Version: - 5.5 Released in 2001 6.0 Released in 2002 6.5 Released in 2003 7.0 Never Released 8.0 Released in 2004 8.2 Released in 2005 9.2 Released in 2007 9.5 Released in 2007 10.0 Released in 2009 11.0 Released in 2011(this version is called as UFT: - Unified Functional Tester) 11.5 Beta version 24/12/2012 Scripting Language: - VB script, java script, Perl script
  • 4. Note: - While latest versions of QTP supports all most all versions. License in QTP: - Seat license: - it is 1:1 license (this is single user license) Concurrence license: - This is a network based license which can share by all the machines in net work. Launching QTP: -*** Step 1: - currently we are using client license, so we need to connect to the client machines. We can connect to the client machine with help of Citrix access get way/ VAP/ Remote Desktop (MSTSC) Step 2: - Click on start > All Programs > Quick Test Professional > select Quick Test Professional Step 3: - While lunching QTP it verifies QTP license and add-in license Step 4: - It Opens add- in Manager Windows with add-ins Step 5: - Select required add- in and click ok button. Add-in Manager: - > It displays all the available add-ins, by default Quick Test Professional provides ActiveX, VB, and Web Note: -by default QTP supports windows environment and hence it is not showing is add-in manager window. > Add-in manager is used to select required environment (Add-in) to make compatible with required environment. > Apart from all this add-ins, if user wants any extra add-ins then user need buy from HP and install.
  • 5. Architecture of QTP: - QTP window is divided in to bellow parts. 1. Test Pane 2. Active Scripts 3. Data Table 4. Information Pane 5. Debug viewer Pane 6. Missing resource Pane 7. Tool option 1. Test Pane: - It is an area where we can write a new test script or to open existing test scripts. It is divided in to 2 views 1> Expert view: - It displays test script in VB Script format 2> Keyword view: - it displays test script in GUI format. It is divided into bellow views 1. Item: - displays fields names 2. Operation: - Displays operation names (Actions performed) 3. Value: - it displays test data. 4. Documentation: - it displays a sentence about item, operation and value. Note 1: - If we do any operation in expert view it effects to keyword and vice versa Note 2: - If we have any syntax errors in expert view not able to navigate to keyword view Note 3: - We can also design test scripts from keyword view. 2. Active Screen: - it is displays a screen shot for each and every VBScript statement. (view menu --> Active Screen) 3. Data Table: - It holds multiple Test Data. It is looks like ms-excel sheet (it contains 65, 536 rows and 256 columns). By default data table provides following 2 sheets 1.Global, 2. Action1 4. Information Pane: - (Navigation:- view menu--> Information ) > It displays syntax error massages. When we save test script. Note: - After save a test script QTP internally compiles the script and display syntax errors in information pane > Information pane contains bellow information Details: - It displays syntax error information Item: - It displays script name Action: - It displays Action name Line no: - It displays error line number 5. Debug viewer Pane: - It is used to find the logical errors and variable values during script execution debug viewer) (view 6. Missing resource: - It displays not available file path which we associated to test script. 7. Tool option: - these are menu options where we can select required menu options. QTP Chapter III Introduction to VBScript Display user defined message: MsgBox Function: -It displays given message and waits for the user to click OK button or close dialog Ex: - MsgBox “Welcome to QTP World” Comments in QTP: - By using single cots („) user can give the comments for scripts Display Message with Required Dialog Title and Buttons: -
  • 6. Syntax: -MsgBox “<message>”, button no, “<dialog title>” Ex: -MsgBox “Welcome to QTP World”, 0 “sample” Here: - 0 is the number for the different types of buttons we have 0, 1, 2, 3, 4, 5, 16, 32…etc. go to MsgBox help by pressing function1 (F1). “Sample” is dialog title. Print Statement: - It displays user given message in Quick Test Print Log window It doesn‟t require any user interaction It will works in QTP only Note: - MsgBox is defined in VBScript Print statement defined in QTP Display a message and Close: -** Set obj= CreateObject (“Wscript.Shell”) obj.Popup “Welcome to QTP World”, 5, “Sample” Here: - number 5 is seconds to close the popup Reading Values during runtime: - InputBox: -it displays a prompt and waits for the user, to enter text and click OK/ Cancel button Syntax: - <variable>= InputBox (“<message>”) Ex: - Val = InputBox (“Enter any Value”) MsgBox Val Operators: - Types of VBScript Operators: - 1. Arithmetic Operators 2. Assignment Operator 3. Comparison Operator 4. Concatenation Operators 5. Logical Operators Arithmetic Operators: - These are used to perform Mathematical operations on given values. 1. ^ operators: -It raises a number to the power of an exponent Ex: - MsgBox 2^3 „returns 8 (2*2*2) 2. * operators: - Multiplies Ex: - MsgBox 2*3 „returns 6 3. / operators: - divides Ex: - MsgBox 2/3 „returns 0.5(Float value) 4. operators: - divides Ex: - MsgBox 2/3 „returns 0(Integer value) 5. MOD operators: - divides Ex: - MsgBox 7 mod 5 „returns 2 (7 divided by 5) 6. + operators: - Sum of given number 7. - operators: - Finds difference between given number
  • 7. Assignment Operator: - = operator: - assigns a given value to a variable Ex: - Val = 10 MsgBox Val Comparison Operator: - These are used to compare two given values Ex: - Val1=10 Val2 = 20 MsgBox Val1 < Val2 „Returns True MsgBox Val1 > Val2 „Returns False MsgBox Val1 <> Val2 „Returns True MsgBox Val1 = Val2 „Returns False Concatenation Operator: - & operator: -It concatenates/ appends to given values Ex: - Val1= “Hi” Val2 = “Bye” MsgBox Val1 & Val2 (Without space) MsgBox Val1 &” ” & Val2 (With space) Logical Operator: - AND operator: - Perform logical conjunction on 2 given conditions OR operator: - Perform logical disjunction on 2 given conditions NOT operator: - Perform logical disjunction on 2 given conditions
  • 8. If….Then….Else….If: - Maintaining conditional statement, in another conditional statement Syntax: - If<condition> Then <Statement> Else If<condition>Then <Statement> End If End If Ex: - Apply If….Then….Else….If to bellow scenario, Do you know testing tool course. If yes then find do you know QTP. If QTP know then display a message Try for JOB. If QTP doesn‟t know then display a message “Go to login f1 to learn QTP”. If testing tool doesn‟t know then display a message “Got login f1 to learn TT”. Val2 = InputBox ("Do you know Testing Tools?") If Val2="yes" Then Val3= InputBox ("Do you know QTP?") If val3="yes" Then MsgBox "Try for job" Else MsgBox "Go to login F1 to learn QTP" End If Else MsgBox "Go to Login F1 to learn TT" End If Select….Case: - It is used to execute a group of statements depends on multiple conditions Syntax: - Select Case <variable> Case 1 <condition> <Statement> Case 2 < condition > <Statement> Case 3 < condition > <Statement> Case Else „Optional <Statement> Ex: -Display one number and display a day name Val = InputBox ("Enter any number") Select Case Val Case 1 MsgBox “Sun Day" Case 2
  • 9. MsgBox "Mon Day" Case 3 MsgBox “Tue Day" Case 4 MsgBox "Wed Day" Case 5 MsgBox "Thu Day" Case 6 MsgBox "Fri Day" Case 7 MsgBox "Sat day" Case Else MsgBox "Invalid Number" End Select Variable Declaration: - Variable: -It is a storage place where we store variable. Declaration: -We declare the variable by using DIM statement. Dim Var1, Var2… Note: - **** 1. Variable names should be meaning full 2. Variable name should explain what type of data we are storing in it Ex: - If store INTIGER then we starts with „i‟ If store STRING then we starts with„s‟ If store DOUBLE then we starts with„d‟ If store BOOLEAN then we starts with „b‟ If store DATE then we starts with „dt‟ If store TIME then we starts with„t‟ 3. Variable names are not case sensitive but we follow standards 4. Variable names starts with small latter, if it contains multiple words then second word on wards the first latter should be a capital latter Ex: -Dim sEmpName, dEmpSal, dtDob, iEmpId…. 5. Default variable is EMPTY 6. When we give the values (numbers) from InputBox for „+‟ operator it treats as String Integer and concatenates the values. For „-„, „*‟, „/‟ operators converts the numbers from String Integers into integer values and do the mathematical operations 7. VBScript variables are variant data type (any kind of data) Ex: -Variable: - MsgBox Krishna + sreekar „Returns 0 (zero) MsgBox Krishna - sreekar „Returns 0 (zero) MsgBox Krishna * sreekar „Returns 0 (zero)
  • 10. MsgBox Krishna / sreekar „Returns Overflow error Massage Strings: - MsgBox “Krishna” + “sreekar” „Returns Appends / concatenates the strings MsgBox “Krishna” - “sreekar” „Returns Error msg as not able to perform String subtraction MsgBox “Krishna” * “sreekar” „Returns Error msg not able to perform String Multiplication MsgBox “Krishna” / “sreekar” „Returns Error msg not able to perform String Division Strings and Variable: - MsgBox “Krishna” + sreekar „Returns krishna MsgBox “Krishna” - sreekar „Returns Error MsgBox “Krishna” * sreekar „Returns Error MsgBox “Krishna” / sreekar „Returns Error String Integers: - MsgBox “10” +”20” „Returns 1020- appends/ concatenates MsgBox “10” -”20” „Returns -10 MsgBox “10” *”20” „Returns 200 MsgBox “10” /”20” „Returns 0.5 String Integers and Numbers: - MsgBox “10” + 20 „Returns 30 MsgBox “10” - 20 „Returns -10 MsgBox “10” * 20 „Returns 200 MsgBox “10” / 20 „Returns 0.5 String and Numbers: - MsgBox “krishna” + 20 „Returns Error Massage MsgBox “krishna” - 20 „Returns Error Massage MsgBox “krishna” * 20 „Returns Error Massage MsgBox “krishna” / 20 „Returns Error Massage In VBScript declaring variables are not mandatory, But we are declaring [Q: - Is variable declaration is mandatory in VBScript? answer is no then next...Q: - Why?] Option Explicit: -*** It displays error massage for undefined variable names. Option Explicit is must declared in the first line of the program. Ex: - OptionExplicit Dim sEmpname sEmpName “sreekar”
  • 11. MsgBox sEName „Returns Error Massage for not defined sEName variable Note: - Variable names should not be a KEY word Loop Statement: - These are used to execute a group of statements for multiple times VBScript Loop Statements: - 1. For… Next 2. While… Wend 3. Do… Loop For…Next: - It executes a script for required number of given times Syntax: - For <variable> = <Start Position > To < End Position > [Step] <Statement> [ExitFor] Next {Here written in [] are optional} Ex: - Display a massage “QTP” for 5 times For index = 1 To 5 MsgBox index Next > In bellow code a and z treats as variable returns empty values so answer is 0 For index = a To z MsgBox index Next > In bellow code a and z treats as variable returns empty values so answer is 0 For index = “a” To “z” MsgBox index „Returns error massage Next Ex: - Display numbers from 5 to 10 > In bellow given string integers are converts in to integers For index = “5” To “10” MsgBox index Next STEP Command: Ex: - For index = 1 To 5 Step 3 MsgBox index „Returns 1, 3 Next Ex: - Display even numbers 2 to 10 For index = 2 To 10 Step 2 MsgBox index „Returns 2, 4, 6… Next
  • 12. Ex: - Display odd numbers from 1 to 10 For index = 1 To 10 Step 2 MsgBox index „Returns 1, 3, 5… Next Ex: - Display numbers from 5 to 1 For index = 5 To 1 Step -1 MsgBox index „Returns 4, 3… Next ExitFor: - Ex: - For index = 1 To 10 Step 2 MsgBox index „Returns 1 and exits from For loop ExitFor Next Ex: - For index = 1 To 10 Step 2 MsgBox index If index = 3 Then ExitFor EndIf Next While… Wend: - It execute group if statements until condition is True Syntax: - While <condition> <Statement> Wend Ex: - Display a massage “QTP” for 5 times index = 1 While index <= 5 Print "QTP" index = index+1 Wend
  • 13. Ex: -Display numbers from 1 to 10 index = 1 While index <= 10 Print index index = index+1 Wend Ex: - Display odd numbers from 1 to 10 index = 2 While index <= 10 Print index index = index+2 Wend Do… Loop: - It executes group statement until condition becomes True Syntax: - Do <condition> <Statement> Loop While <condition> Ex: -Display a massage “QTP” for 5 times index = 1 Do Print "DTP" index = index+1 Loop While index = 5 Ex: -Display numbers from 1 to 10 index = 1 Do Print index
  • 14. index = index+1 Loop While index <= 10 Functions Functions are used for scripts reusability 1. Built-in Functions 2. User Defined Functions Built-in Functions: - These are pre defined by VBScript Access functions in QTP Category as Functions Library as Built-in Function find the functions in StepGenerator Insert MenuOperation drop down Note 1: - Function names are not Case Sensitive
  • 15. Note 2: - We follow standards like function name starts with capital later if it contains multiple words then 2nd word on words 1st later should be a capital latter 1. Abs() [Absolute]: -It returns absolute value to a given number Ex: - MsgBox Abs (10) „Returns 10 MsgBox Abs (-10) „Converts the –ve in to +ve „Returns 10 MsgBox Abs (10.56) „Returns 10.56 MsgBox Abs (-10.56) „Returns 10.56 MsgBox Abs ("10") + Abs ("20") „Returns 30 – Converts the string into Integer Value 2. Asc(): - It returns ASCII to given Character Ex: -MsgBox Asc ("a") „Returns 97 MsgBox Asc ("z") „Returns 122 MsgBox Asc ("A") „Returns 65 MsgBox Asc ("Z") „Returns 90 3. Chr(): - It returns ASCII to given Character Ex: - MsgBox Chr (97) „Returns a MsgBox Chr (122) „Returns z MsgBox Chr (65) „Returns A MsgBox Chr (90) „Returns Z 4. CInt(): - It Converts String Integer in to Integer Ex: - iVal1 = "10" iVal2 = "20" MsgBox iVal1+iVal2 ' Returns 1020 MsgBox CInt (iVal1) +CInt (iVal2) ' Returns 30 Ex: - 10.56 the CInt Converts into 11 iVal1= "10.56" iVal2= "-20.78" iVal1= iVal1*100 iVal2= iVal2*100 MsgBox (iVal1+iVal2) / 100 5. CStr(): - It converts given value into Strings iVal1 = 10 iVal2 = 20 MsgBox iVal1+iVal2 Returns 30 MsgBox CStr (iVal1) + CStr (iVal2) „Returns 1020 MsgBox CStr (iVal1) – CStr (iVal2) „Returns -10 Date and Time Factions 6. Date: - It returns current system Date in MM/DD/YYYY format Ex: - MsgBox Date
  • 16. 7. Time: - It returns current system Time in HH/MM/Sec format 8. Ex: - MsgBox Time 9. Now(): - It returns current system Date & Time Ex: - MsgBox Now 10. DateAdd(): - This function add/ subtracts given date or time, given date and time Ex: - MsgBox DateAdd ("yyyy", 1, Date) „Returns Year with adding 1 to the current year MsgBox DateAdd ("q", 1, Date) „Returns Quarter with adding 1 to the current Quarter MsgBox DateAdd ("m", 1, Date) „Returns Month with adding 1 to the current Month MsgBox DateAdd ("y", 1, Date) „Returns Day of year with adding 1 to the current Day of year MsgBox DateAdd ("d", 1, Date) „Returns Day with adding 1 to the current Day MsgBox DateAdd ("w", 1, Date) „Returns Weekday with adding 1 to the current Weekday MsgBox DateAdd ("ww", 1, Date) „Returns Week of year with adding 1 to the current Week of year MsgBox DateAdd ("h", 1, Date) „Returns Hour with adding 1 to the current Hour MsgBox DateAdd ("n", 1, Date) „Returns Minute with adding 1 to the current Minute MsgBox DateAdd ("s", 1, Date) „Returns Second with adding 1 to the current Second MsgBox DateAdd ("yyyy", 8000, Date) „Returns Error because year above 10000 11. DateDiff (): - This function is used to find the difference in between given 2 dates or 2 times. In day, Month, Year, hour, Minutes, Seconds intervals Syntax: -MsgBox DateDiff (Interval, date1, date2) MsgBox DateDiff ("d", Date,"01-01-2013") 'Returns -2 (My System date 03-01-2013) MsgBox DateDiff ("d", "01-01-2013", Date) 'Returns 2 (My System date 03-01-2013) 12. DatePart(): - It is used to retrieve required interval date or time from given date or time Syntax: - MsgBox DatePart (Interval, Date/ Time) MsgBox DatePart (“d”, Date) MsgBox DatePart (“m”, Date) MsgBox DatePart (“yyyy”, Date) 13. Day(): - It retrieves day from given date Ex: - MsgBox Day (Date) 14. Month(): - It retrieves Month from given date Ex: - MsgBox Month (Date) 15. MonthName(): - It retrieves the name of the month from given number from 1 to 12 Ex: - MsgBox MonthName (Date) 16. Year(): - It retrieves Year from given date Ex: - MsgBox Year (Date) 17. WeekDay(): - It retrieves Weekday from given date Ex: - MsgBox WeekDay(Date) 18. WeekDayName(): - It retrieves WeekDayName from given number(1-7) Ex: - MsgBox WeekDayName (1) „Returns Sunday
  • 17. MsgBox WeekDayName (WeekDay (Date)) „Returns current WeekDayName Boolean Functions: - 19. IsDate (): -It retrieves Boolean value for given expression is date or not. It returns True if given value is date else false Ex: - MsgBox IsDate (“Suresh”) „Returns False MsgBox IsDate (“3-01-2013”) „Returns True 20. IsEmpty (): -It retrieves Boolean value for given value is Empty or not. It returns True if given value is Empty else false Ex: - Dim val1, val2, val3 Val1 = 10 Val2 = Null MsgBox IsEmpty(Val1) „Returns False MsgBox IsEmpty(Val2) „Returns False MsgBox IsEmpty(Val3) „Returns True 21. IsNull (): -It retrieves Boolean value for given value is Null or not. It returns True if given value is Null else false 22. IsObject (): - It retrieves Boolean value for given expression is Object or not. It returns True if given value is Object else false Ex: - Dim Val1, Obj Val1 = 10 Set obj = CreateObject (WScript. Shell) MsgBox IsObject (Val1) „Returns False MsgBox IsObject (Obj) „Returns True 23. IsNumeric (): - It retrieves Boolean value for given expression is Numeric or not. It returns True if given value is Numeric else false Ex: - Dim val1, val2, val3 Val1 = 10 Val2 = 13.45 Val3= “suresh” MsgBox IsNumeric (Val1) „Returns True MsgBox IsNumeric (Val2) „Returns True MsgBox IsNumeric (Val3) „Returns False String Functions 24. Left (): - It returns number of characters from left side of a given string Ex: - sString = “My Name is Suresh” MsgBox Left (sString, 4) „Returns My N 25. Right (): - It returns number of characters from right side of a given string Ex: - sString = “My Name is Suresh” MsgBox Right (sString, 4) „Returns resh 26. Mid (): -*** It returns a substring from a given String System: - MsgBox Mid (String, start position [, Number of characters]) Ex: - Ex: - sString = “My Name is Suresh”
  • 18. MsgBox Mid (sString, 4, 7) MsgBox Mid (sString, 4) MsgBox Mid (sString, 100) MsgBox Mid (sString, 100, 1) sString = "Rs:1000/-" MsgBox Mid (sString, 4, 7) ' Returns 1000/- MsgBox Mid (sString, 4, 4) ' Returns 1000 'To get any number MsgBox Mid (sString, 4, Len (sString)-5) ' Returns 1000 27. Len(): - ***It returns number of characters from given string Ex: - sString = “My Name is Suresh” MsgBox Len (SString) 28. Replace(): - This function is used to replace a text with another text in given text Syntax: - Replace (String, replacing text, new text) Ex: - sString = "My name is suresh" MsgBox Replace (sString, "suresh", "babu") MsgBox Replace (sString, "is", "") 29. LTrim(): - It removes all spaces from Left side of a given string [Ex: - MsgBox LTrim(sString)] 30. RTrim(): - It removes all spaces from Right side of a given string [Ex: - MsgBox RTrim(sString)] 31. Trim(): - It removes all spaces from Left and Right side of a given string 32. LCase(): - It converts given text in lower case letters 33. UCase(): - It converts given text in upper case letters Ex: - MsgBox LCase (“My Name Is SURESH”) MsgBox UCase (“My Name Is SURESH”) 34. StrReverse(): - ***It displays / retrieves a reverse text for given string/ text sString= “suresh” MsgBox StrReverse (sString) Without using StrReverse:- Dim sString sString = “suresh” For index = Len (sString) To 1 Step -1 str = str & Mid(sString, index,1) Next Print str 35. InStr() and InStrRev(): - It retrieves the first occurrence position of the given text in actual text sString = “My name is suresh your name is babu” MsgBox InStr (sString,”suresh”) „Returns the position of„s‟ from suresh MsgBox InStr (sString,”name”) „Returns 4 first occurrence of name MsgBox InStr (sString,”babu”) „Returns 0 MsgBox InStrRev (sString,”name”) „Returns 24 Last occurrence of name MsgBox InStr (14, sString,”babu”) „Returns 0: suresh is not found from 14th position 36. StrCompp(): - It is used to compare two given strings
  • 19. 37. String(): - It is used to display the string in number of times Ex: -MsgBox String (5, *) „Returns ***** 38. TypeName(): -It returns the data type for the given variable Ex: - Dim Val Val = 10 MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns Integer Val = 10.05 MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns Double Val = "Suresh" MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns String 39. Split (): - It is used to split the text with given delimiters 40. Arrays Arrays are used to store multiple values in a variable Declaration: - 1> Static Array declaration Dim sName (3) 2> Dynamic Array declaration Dim sName ()
  • 20. Scripts
  • 21. 9. Write a script to find the SUM of odd number up to given number 10. Write a script to find the SUM of even number up to given number 11. Write a script to find given Text/ Numbers is palindrome or not [madam reverse madam] sString = UCase(InputBox("Enter the String/Number:"))
  • 22. rString = StrReverse(sString) If StrComp (sString,rString) = 0 Then MsgBox “It is a Palindrome" Else MsgBox “It is Not a Palindrome" End If 12. Write a script to find Factorial of given number [5*4*3*2*1=120] Option Explicit Dim iVal1 ,iVal2, iFact iVal1= Int (InputBox ("Enter a Number :")) iFact = 1 iVal2=1 Do while iVal2 <=iVal1 iFact = iFact * iVal2 iVal2=iVal2+1 Loop Print iFact 15. Write a script to display * as bellow with respect to given value Option Explicit Dim iVal, sString,index,index1 sString="" iVal = 5 ' InputBox ("Enter a Number") For index = 1 To iVal For index1 = 1 To index sString = sString & " * " Next
  • 23. Print sString sString="" Next 16. Write a script to display * as bellow with respect to given value 17. Write a script to display * as bellow with respect to given value 9 programs to write for this 1) Pro1 Option Explicit Dim iVal, sString,index,index1 sString="" iVal = 5 ' InputBox ("Enter a Number") For index = iVal To 1 Step-1 For index1 = 1 To index sString = sString & " * " Next Print sString sString="" Next 2) Pro 2 Option Explicit Dim iVal, sStar,index,index1,iSpace iVal = 5 For index = iVal To 1 Step-1 For index1 = 1 To iSpace sStar= sStar & " " Next For index1 = 1 To index sStar = sStar & "*" Next Print sStar sStar ="" ' Removing the value after print iSpace= iSpace + 1' Increasing the spaces for next iteration Next '############################################################################################# '######### Program to write a character in a particular pattern using VBS ######################### '############################################################################################# 'Declaring variables Dim MainCounter,TempCounter,sStr,sTempStr,sMainStr,PatternChar 'Initializing variables PatternChar = "*" sStr = "" 'Reading from Input and initializing MainCounter = InputBox("Enter any number") If MainCounter = "" Then MainCounter = 9 End If MainCounter = Abs(MainCounter)
  • 24. TempCounter = MainCounter 'Looping twice the supplied value to draw the pattern and reverse it For MainIndex = 1 to MainCounter * 2 'Increase the tempCounter for drawing the pattern and 'Decrease the tempcounter to draw the pattern in reverse order If Abs(MainIndex) <> 1 and Abs(MainIndex) <> MainCounter + 1 Then If MainIndex <= MainCounter Then TempCounter = Abs(TempCounter) - 1 Else TempCounter = Abs(TempCounter) + 1 End If End If sTempStr = "" iSpace = "" 'Looping to Create the pattern for a single row For indx = 1 to TempCounter sTempStr = sTempStr & PatternChar Next 'manipulating space for a row iSpace = Space((Abs(MainCounter)-Abs(TempCounter)) * 2) 'Adding the space for a single row sStr = sStr & sTempStr & iSpace & sTempStr & vbNewline Next 'sStr= sStr & vbNewline & StrReverse(sStr) 'MsgBox sStr 'Writing the pattern to a txt file in D drive Dim filesys, testfile Set filesys = CreateObject("Scripting.FileSystemObject") Set testfile= filesys.CreateTextFile("d:PatternDrawnFromVbs.txt", True) testfile.WriteLine sStr testfile.Close Example: - write a script to retrieve India in given string “I love India” sVal = "i love InDiA" sVal = Split(s," ") MsgBox sVal(UBound(s)) Application (Window, VB, Java, Dot Net, Web) Script Application Script: - Script 1: -Write a script to enter student details Note: - Before writing a VBScript with respect to application we need to know bellow 5 information‟s 1. Object Name 2. Object Class Name 3. Object Parent Object Name
  • 25. 4. Object Parent Object Class name 5. Method Name. To perform operation Note: - Object SPY To know about the object use Object SPY in TOOL MENU For Web Application iHwnd = Browser("Gmail")GetROProperty("hwnd") „ first 2 lines to activate the browser Window("hwnd:="&iHwnd).Activate Browser("Student").Page("Student").WebEdit("").Set "Sreekar" Browser("Student").Page("Student").WebEdit("Course").Set "QTP" Browser("Student").Page("Student").WebButton("Submit").Click QTP Chapter IV Chapter - 4 Object Repository: - It is a storage place, where we store objects and their information Note: - Before designing or executing a test script we need to add objects to Object Repository for recognition of objects by QTP. Else QTP is not able to understand the objects displayed the errors while executing the script Object Repository select Navigation: - Resource menu Or Click Object Repository Or Cntrl + R Application under test [AUT]: -It means which application we need to test is called AUT. Adding Objects to Object Repository: - We can add objects to Object Repository by manually or by Recording Adding Objects to Object Repository By Manually: - Click Ad Objects to local icon Open Object Repository Open Application under test [AUT] Select required object with the help of handler pointer If it is parent object displays Filter Options [Selected objects only, Default Object Click OK button Select required option Click OK Button. Types, All Object Types, Selected Object Types] Note: - Every Action maintains individual Object Repository in Object Repository
  • 26. Options in Object Repository: - We have Operations as follows ADD: - We can add objects to Object Repository by manually or by Recording Select Rename Right Click on required object Rename: - Open Object Repository Check YES in Select Delete Right Click on required object Delete: - Open Object Repository Confirmation Note-1: - Before executing the script, we make sure that the AUT is open Note-2: - If we Re-name the Object name in Object Repository it affects to test script Note-3: - If we do any modification on objects in test script it will not/ doesn‟t affect to Object Repository Note-4: - If we save a test script Object Repository also saves for the same test script Note-5: - We can drag objects from Object Repository to test script. We write test script in Keyword View. Types of Object Repository: - We have two types of Object Repository 1. Local Action (or) per Action Object Repository 2. Shared Object Repository Local Action (or) per Action Object Repository: - Maintaining Repositories in Action independent is called as Local Action (or) Per Action Object Repository. Ex: - A1R (Action Repository) Objects Objects >A2R (Action Repository) Objects >A3R (Action Repository) Note1: - Local repository saves the file with “.mtr” [Mercury Test Repository] while save the script Shared Objects Repository: - Creating and maintaining a single repository for multiple actions called as Shared Object Repository. EX: - Creating Shared Creating Shared Object Repository: - Export Local File Add object to Object Repository Open Object Repository Open AUT Save the file in required path with “.tsr” [Test Shared Repository] Objects After creating a shared ObjectRepository we need to associate to required test script for use. We can associate in bellow ways 1. By Navigation 2. By Scripting By Navigation: - Browse and Open Click Add Button Associate Repositories Repository Open required test script click OK button select Required Action SOR [Shared Object Repository] By Scripting: - Syntax: - RepositoriesCollection.Add “SOR File Path” Ex: - RepositoriesCollection.Add “D:sureshORxxxx.tsr”
  • 27. Note1: - RepositoriesCollection.Add is a static association i.e. if we write the statement in action, then it associate to action1 Repository Note2: - After script execution SOR disassociate by default. Note3: -For better maintenance we use only one shared object repository. Working with Shared Object Repository/ Operations in SOR: - Directly we are not able to modify any operations on SOR file. We use Object Repository Manager [ORM]. Brows and open required SOR Click open folder icon object Repository Manager Navigation: -Resource Menu Click Save. on Objects perform required operations (Add, Rename, Delete) click Enable edit Icon file Note: - if we do any modification in SOR file it changes in all associated object repositories. Merging Shared Object Repository: - [we won‟t use] Navigation: -Browse and Open select Object Repository Merge tool Tools select ORM Resources menu save the file .tsr click save icon primary and secondary files Types of Objects With respect to OR we have 2 types of objects. 1. Test objects 2. Runtime Object Test Object: -Objects which are in OR are called as test objects. Runtime Objects: - objects which are in AUT are called as runtime objects. Note: - Every Test object is a run time object. Note: - Every runtime object may or may not be a test object Working with Test Objects: - 1. GetToProperty() 2. GetToProperties() 3. SetToProperty() GetToProperty (): - It is used to retrieve test object given, property value during run time. Syntax: - Ex: - MsgBox dialog(“login”).WinButton(“Help”).GetTOProperty (“Text”) „Returns Help MsgBox Dialog(“login”).GetToProperty(“text”) Note: - 1. If given property is invalid or not available in Object Repository. It retrieves EMPTY. 2. Property names are not case sensitive GetTOProperties(): - It is used to retrieve multiple property names and its values for a test object, from OR during run time. Ex: - MsgBox Dialog(“login”).GetTOProperties() „ Returns ERROR {Script 2 is an example for this} Script No 2: - Write a script to retrieve property names and values per a login object Set sPropertyLst = Dialog("Login").GetTOProperties 'MsgBox sPropertyLst.Count For index = 0 To sPropertyLst.Count-1 Print sPropertyLst(index).Name & VbTab & sPropertyLst(index).Value Next Set sPropertyLst = Nothing SetTOProperty(): - It is used to change the test object property values during run time. Whenever object properties are changing at runtime we use this method:
  • 28. Syntax: - Ex: - Dialog(“login”). SetTOProperty “text”,”sreekar” Working with Run Time Objects: - GetROProperty(): - It used to retrieve run time object property value during run time Syntax: - Ex: - MsgBox Dialog(“login”).GetROProperty(“text”) [Above code will retrieve QTP identified properties {in object spy}] Note: -*** If we want to retrieve Native Properties for an object we use “Object()” Syntax: - [Native Properties are developers given properties {in object spy}] Work Out: - Go through the button, text box, browser, page, link for Identified Properties and Native Properties Adding objects to OR by Run Time Types of Recording: - 1. Normal or Standard Recording 2. Analog Recording 3. Low-Level Recording Normal or Standard: - It is used to record standard objects like Window, Web, VB, Java, Dot Net…Etc. select desired environment (Web/ Windows) Record Button Navigation: - Open application (AUT) observe that script is generated in click Stop perform operations on AUT Click OK Click Apply test pane and respective objects added in OR. Analog Recording: - Analog recording is used to record diagrams, signatures, graphs…etc. It generates a single statement for every start and stop recording. Navigation:- Click Select Environment window or web Click Recording in QTP Open AUT Select Record relative to the following window Select Analog Recording from Automation Menu OK perform Click start analog record button with help of handler point select AUT radio button Click Stop Recording in QTP. operation Low-Level Recording: - It is used to record minimum operations on non-supported environments Select Web/Windows Select desired Environment Click Record in QTP Navigation: -Open AUT click STOP Recording. Perform operations on AUT Low Level Recording from Automation Menu Object Repository Standards: -
  • 29. 1. What is an Object? 2. How QTP is recognizing objects? 3. What is OR? 4. What is your approach for writing a test script? 5. What is the default OR? 6. How do you add object to OR? 7. What is extension of PerAction of Local repository? 8. How do you create local Repository? 9. How many objects I can store in QTP test script?—2MB 10. How to create SOR? 11. What is difference between PerAction and SOR? 12. How many SOR files you have created for your project? 13. What is the file extension of SOR file?--.tsr 14. Where do you maintain all SOR files in your testing process? 15. Have you merged SOR files? 16. Why do you go for merging SOR files? 17. Can we do merge more than 2 SOR files at a time, if it is not then how do you merge more than two SOR files? 18. How do you merge PerAction Repository? 19. How many objects are there and what are they?
  • 30. 20. How do you create test objects? 21. What are the methods you can find for Test Objects? 22. What is the difference between GetToProperty and GetToProperties method? 23. Write a test script for retrieving multiple properties and their values for a object? 24. How do you handle, if test object properties are dynamically changing during run time? 25. How do you retrieve object information during runtime? 26. What is the deference between GetToProperty and GetROProperty? 27. Which method you are using for retrieving object information GetToProperty or GetROProperty? 28. Who will create SOR? 29. How do you work with SOR? QTP - Chapter V Check Points Check points are used to validate Object Properties, Comparing Text, Comparing Images, Validate Database…etc. [OR] Check point is a verification point, it takes expected result from the user and compares with actual results during execution and provides test results. Types of Check Points: - There are 9 Checkpoints available in QTP: 1. Standard check point 2. Text check point 3. Text area check point 4. Bit map check point 5. Data base check point 6. Image checkpoint 7. Table checkpoint 8. XML Check point (from Application) 9. XML Check point (from Resource) 1. Standard Checkpoint: It is used to validate object properties Navigation: -Open AUT Click Record in Qtp Insert Menu Check Point Select Standard Checkpoint Select Expected properties and With help of handler Select Required Object Click on OK button Values Click on OK Button. Syntax: - Ex: - Dialog (“Login”) .WinButton (“ok”). Check Checkpoint (“ok”) Draw Backs of Check Checkpoint: - All Checkpoint syntax is same and hence unable to find what kind of Checkpoint it is. Copied checkpoint statement does not run in another script (Action) And hence above are the reasons mostly we are not using any checkpoints, we convert checkpoints scenarios in to VBScript Converting check points to VBScript: If Window (“Flight Reservation”).WinButton (“insert Order”).GetROProperty (“enabled”)=”true” Then Window (“Flight Reservation”).WinButton (“insert Order”).Click Else MsgBox “Insert Order is disabled” 2. Text Checkpoint: -It is used to validate given text in given object With Select Text Checkpoint Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Select required Click on Configuration Button Click on OK button help of handler Select Required Objet Stop Recording Click on OK Button text
  • 31. Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”) Converting check points to VBScript: In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn QTP validate QTP is exist in notepad sText = Window (“notepad”).WinEditor (“Edit”).GetROProperty (“Text”) If InStr (sText, “qtp”) > 0 Then MsgBox “Text is found” Else MsgBox “Text is Not Found” 3. Text Area Checkpoint: - It is used to validate given text is exist in between given text Select Text Area Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Stop Recording Click on OK Button Select Checked Text, Check After Text, Checked Before Text click on OK Button Select Required Text Checkpoint Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”) In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn QTP validate QTP is exist in notepad H.W:- Validate Sreekar is existing in Between name and QTP 4. Bitmap Checkpoint: -It is used to compare two images Select Bit Map Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Minimize or Close expected Stop Recording click on OK Button Select the Expected Image Checkpoint Analyze the Result Run Script Open actual image[which need to Test] Image Scripts related to Standard Checkpoint Check Points Scripts related to Standard Checkpoint: Script No3: - Write a script to validate Calculator Functionalities
  • 32. Script No4: - Write a script for Object Existence [Validation of Vehicle Insurance] Scripts related to Standard Checkpoint Check Points How to get the Menu Options if we are not able to find with Obj Spy? Script: - ********** Write a script to Select MENU Options Method 1: - In Menu Options we cannot identify the objects with Object Spy through Recording we are going to generate the script Window ("Flight Reservation").Activate Window ("Flight Reservation").WinMenu("Menu").Select "File;Open Order..." Window ("Flight Reservation").WinMenu("Menu").Select "Help;About..." Method 2: - Without Recording we get the Menu items by using short cut keys
  • 33. Window ("Flight Reservation").Activate Window ("Flight Reservation").Type micAltDwn + "h" + micAltUP + "a" QTP - Chapter V Scripts related to Standard Checkpoint Check Points Script No12: - Write a Script to find given value is exist in DROP DOWN Example: -kesinenitravels.com validate “HYDERABAD” is exist in from drop down Method 1:- Option Explicit Dim sExpItem,iFlag,iItemCnt,index,sItemName,obj sExpItem = "KURNOOL" iFlag = 0 Set obj = Browser("Kesineni").Page("Kesineni") iItemCnt = obj.WebList("From").GetROProperty("items count") For index = 1 To iItemCnt sItemName = obj.WebList("From").GetItem(index) If sItemName = sExpItem Then Print "Item is Found" iFlag = 1 Exit for ' If we did not declare this the loop will iterate after getting the result also End If Next If iFlag = 0 Then print "Item Not Found" 'if we give it within for loop it iterates, so we took Flag for this End If Limitation: - Above Logic executes for all items if the items are at end or not found Method 2:- On Error Resume Next „It skips the Errors if any occurs in script running time Set obj = Browser("Kesineni").Page("Kesineni") obj.WebList("From").Select sExpItem If Err.Number = 0 Then „Err.Number will give the script run time ERROR NUMBERS it is VB Utill MsgBox "Item is found" Else MsgBox "Item Not Found" End If Limitation: -If item is not found then result window displays with RUNTIME ERROR which we won‟t accept Method 3:- Question: - Write a script for dropdown On Error Resume Next „It skips the Errors if any occurs in script running time Set obj = Browser("Kesineni").Page("Kesineni")
  • 34. sItemName = obj.WebList("From").GetROProperty("all items") If InStr(sItemName, sExpItem) > 0 Then MsgBox "Item is Found" Else MsgBox "Item Not Found" End If Question: - How do you find Combobox or ListBox items? In Windows based application we have “GetItemCount” In Web based application we have “GetROProperty (―item count‖)” Note:-**** 1. Err.Number: - To identify runtime error number 2. On Error Resume Next: - When we get any error in script execution it skips that line goes to next Scripts related to Standard Checkpoint Check Points Script No13: - Write a script for Rail Reservation Set obj = Browser("Reservation").Pabe("Reservation") obj.WebEdit("Name").Set "Sreekar" obj.WebEdit("Age").Set "32" obj.WebList("Gender").Select "Male" obj.WebList("Name").Select "Hyderabad" obj.WebList("Name").Select "Kurnool" 'Validate default Class If obj.WebRadioGroup("Class").GetROProperty("value") = "AC" Then MsgBox "Default Class is AC" Else MsgBox "Default Class is Not AC" End If „Validate Class Price obj.WebRadioGroup("Class").Select "AC" iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text") iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/- If iTcktPrice = "1000" Then MsgBox "AC Price is 1000/-" Else MsgBox "AC Price Not 1000/-"
  • 35. End If obj.WebRadioGroup("Class").Select "Sleeper" iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text") iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/- If iTcktPrice = "1000" Then MsgBox "Sleeper Price is 500/-" Else MsgBox "Sleeper Price Not 500/-" End If 'Validate No of Tickets iTickets = InputBox("Enter number of Tickets") obj.WebEdit("Tickets").Set iTickets obj.WeButton("Submit").Click iTotalPrice = obj.WebEdit("Total Price").GetROProperty("text") iTotalPrice = Mid(iTotalPrice,4,Len(iTotalPrice)-5) If iTotalPrice = iTickets * iTicketPrice Then MsgBox "Total Price Functionality Validation is Pass" Else MsgBox "Total Price Functionality Validation is Fail" End If iTcktNo = obj.WebEdit("TicketNo").GetProperty("text") If NOT IsEmpty (iTcktNo) Then MsgBox "Ticket Noumber Validation is Pass" Else MsgBox "Ticket Noumber Validation is Fail" End If Scripts Related to Text Checkpoint Ex: - Notepad: - my name is sreekar there is no prerequisite for learning QTP please come here and learn QTP Script No5: -Write a script to Validate Text Existence Ex: - Notepad: Validate sreekar text existence:- Option Explicit Dim sActTxt, sExpTxt sExpTxt = "sreekar" sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty ("text") If InStr(sActTxt, sExpTxt) > 0Then MsgBox "Text is Found" Else MsgBox "Text is Not Found" End If Script No6: -Write a script to find the string number of occurrences Ex: - Notepad: Find sreekar text number of occurrence:- Option Explicit Dim sActTxt, sExpTxt sExpTxt = "sreekar"
  • 36. sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty ("text") MsgBox (Len(sActTxt)- Len(Replace(sActTxt,sExpTxt,"")))/ Len(sExpTxt) Script No7: - Write a script to find the ovals Ex: - Notepad: - Option Explicit Dim sActTxt, iACnt,iECnt,iICnt,iOCnt,iUCnt sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty( "text") iACnt = Len(sActTxt)-Len(Replace(sActTxt,"a","")) iECnt = Len(sActTxt)-Len(Replace(sActTxt,"e","")) iICnt = Len(sActTxt)-Len(Replace(sActTxt,"i","")) iOCnt = Len(sActTxt)-Len(Replace(sActTxt,"o","")) iUCnt = Len(sActTxt)-Len(Replace(sActTxt,"u","")) MsgBox iACnt+iECnt+iICnt+iOCnt+iUCnt Script No8: - Write a script to find number of Alphabets Ex: - Notepad: - Option Explicit Dim sActTxt,index,iCnt, iChrCnt iChrCnt = 0 sActTxt = UCase( Window("Notepad").WinEditor("Edit").GetROProperty( "text")) MsgBox Len(sActTxt) For index = 65 To 90 'upper Case A - Z iCnt = Len(sActTxt) - Len(Replace(sActTxt, Chr(index),"")) iChrCnt=iChrCnt + iCnt Next MsgBox iChrCnt Script No9: - Write a script to find number of strings in a given text [&_ for Continue the line] Option Explicit Dim sActTxt,index,iCnt, iChrCnt sActTxt = "my name is sreekar there is no prerequisite for learning QTP"&_ "Please come here and learn QTP" iChrCnt = 0 sActTxt = Split (sActTxt, " ") MsgBox UBound (sActTxt) + 1 Scripts related to Text Area Checkpoint Script No10: -Write a Script to find given text existence in between given two texts Ex: - Notepad:Find sreekar in between name and QTP Script No11: - Write a script to retrieve Driver letter, File Path and File Name from given Text Option Explicit Dim sActTxt,index,iCnt, iChrCnt sActTxt = "D:sreekarbatch40test scriptssamplesample.mts"
  • 37. MsgBox "Driver Letter is: - " & Mid(sActTxt,1,1) MsgBox "File Name is: - " & Mid(sActTxt,InStrRev(sActTxt,"")+1) MsgBox InStrRev(sActTxt,"") MsgBox "File Path is: -" & Mid(sActTxt,4, InStrRev(sActTxt,"")-4) [Here to find the file path we subtracted 4 {1st 3 {D :} letters and last occurrence of ―‖}] CaptureBitMap: - It is used to take a screen for the given object Syntax: - .CaptureBitMap “Path.bmp/png” Ex: - Capture Login Dialog("Login").CaptureBitMap "E:01 My Scriptslogin.bmp" Capture OK button in Login Dialog Dialog("Login").WinButton("OK").CaptureBitMap "E:01 My Scriptsloginokbtn.bmp" Note: - When we capture child object, QTP captures only child Object Capture Desktop Window ("text:= QuickTest.*").Minimize Desktop.CaptureBitmap("E:01 My ScriptsDesktop.bmp") Window("text=QuickTest.*").Maximize [;- Descriptive Programming] Script No14: - Write a script to Right Click on Notepad editor and select past by using down arrow key Set obj = CreateObject ("WScript.Shell") Window("Notepad").Activate iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x") iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y") Window("Notepad").Activate Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn obj.SendKeys "{DOWN}" ' These things we can write in Loop Wait(1) obj.SendKeys "{DOWN}" Wait(1) obj.SendKeys "{DOWN}" Wait(1) obj.SendKeys "{DOWN}" obj.SendKeys"{ENTER}" For index= 1 To 4 obj.SendKeys "{DOWN}" wait(1) Next Script No15: - Write a script to open an existing notepad right click on it, select ―Select All ―option by pressing/ Sending UP arrow key (in windows 7 it differs) one time, Right Click on Notepad, select copy option by sending Down arrow key for 3 (in windows 7 it differs) times, close the notepad, open a new notepad, Right Click on it select past by sending UP arrow key for 3(in windows 7 it differs) times. SystemUtil.Run "E:01 My Scripts1.txt" Set obj = CreateObject("WScript.Shell") 'Window("Notepad").Activate
  • 38. iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x") iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y") 'Window("Notepad").Activate Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn For index = 1 To 6 obj.SendKeys"{UP}" 'Wait(1) Next obj.SendKeys"{ENTER}" 'Wait(1) Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn For index1 = 1 To 3 obj.SendKeys"{DOWN}" 'Wait(1) Next obj.SendKeys"{ENTER}" Window("Notepad").Close SystemUtil.Run"Notepad" Window("Notepad").WinEditor("Edit").Click iXCord,iYCord,micRightBtn For index2 = 1 To 4 obj.SendKeys"{DOWN}" 'Wait(1) Next obj.SendKeys "{ENTER}" Text Area Checkpoint - Desktop Check Points Script No16: -Write a script to right click on Desktop, select Properties and validate “DESKTOP” Tab Existence in “Display Properties Dialog” if exist then select it. Option Explicit Dim sExpTab,iFlag,sActTab,index,obj,iXCord,iYCord,iTabCnt sExpTab = "Desktop" iFlag = 0 Set obj = CreateObject("WScript.Shell") iXCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("x") iYCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("y") Window("text:=QuickTest.*").Minimize Window("Program Manager").WinListView("SysListView32").Click iXCord,iYCord,micRightBtn Wait(1) obj.SendKeys"{UP}" obj.SendKeys"{ENTER}" iTabCnt = Dialog("Display Properties").WinTab("SysTabControl32").GetItemsCount For index = 0 To iTabCnt-1 sActTab = Dialog("Display Properties").WinTab("SysTabControl32").GetItem(index) If sExpTab = sActTab Then iFlag = 1 Dialog("Display Properties").WinTab("SysTabControl32").Select sExpTab MsgBox "Given Tab is Found and Selected" Exit For End If Next If iFlag = 0 Then
  • 39. MsgBox"Given Tab is Not Found" End If QTP - Chapter VI Chapter VI Working with Test Result We display test results in Test Result window by using Reporter Utility Object We display bellow Types of results: 1. Pass 2. Fail 3. Warning 4. Normal Syntax: - Report.ReportEvent,””,”” We have 4 types of event status 1. micPass (0) 2. micFail (1) 3. micWarning (3) 4. micDone [Normal] (2) Ex: - Reporter.Reportevent micPass, “Validate dialog login exist”,”Dialog login exist” Reporter.Reportevent micFail, “Validate dialog login exist”,”Dialog login not exist” Reporter.Reportevent micWarning, “Validate dialog login exist”,”Dialog login is minimized” Reporter.Reportevent micDone, “execution start”, “Test script execution start” Ex: - If Dialog (“login”).exist=”True” Then Reporter.Reportevent micPass, “Validate dialog login exist”, “Dialog login exist” Else Reporter.Reportevent micFail, “Validate dialog login exist”, “Dialog login not exist” Endif Save text Results in Required Path: - Navigation: - Click Run Button->Select new Run Results folder Radio button->Click Browser->Browse and open required path->Click OK button.->After script execution QTP saved a given folder in given path. QTP - Chapter VII - VIII - IX Utility Objects -->These are predefined by QTP which are used to enhancing scripting Navigation: Insert Menu ->Step Generator -->Select Category as Utility Objects --> Find List of objects in Objects Drop Down Utility Objects: - Navigation: - Insert Menu -->Stepgenerator -->Select Category as Utility Object -->Find List of Utility Objects in object drop down Crypt: - It encrypts the given script generally it is used to enter Secure Password
  • 40. Eg: - Crypt.Encrypt (“mercury”) [:- object. method] --> We can also encrypt the given string with bellow navigation Start --> all programs -->QTP-->Tools -->Password Encoder-->Enter the String -->Click Generate Button-->click Copy Button -->Paste it where needed. Desktop: - It is used to work with desktop ***Note: -To click the radio button [Ex: - winRadioButton (“”).Set] ***Note: - To check the CheckBox we “ON”, “OFF” [Set “ON”/”OFF”] To know whether CheckBox is checked are not go to spy check the Checked value as ON / OFF and assign the value to GetROProperty RandomNumber: - It is used to generate random number with given range Example: - 1. Generate 4 digit random number MsgBox RandomNumber (1000.9999) 2. Generate 5 Characters String For index = 1 To 5 sStr = sStr & Chr(RandomNumber(65,90)) Next MsgBox sStr SystemUtil: - By using this we open and close application and its process during runtime Run: -It is used to open application during runtime Ex: - Open login Dialog SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" 'Open internet explore SystemUtil.Run "iexplore" 'Open internet explorer with URL SystemUtil.Run "iexplore", "www.google.com" 'Open EXCEL SystemUtil.Run "EXCEL" 'Open MS Word SystemUtil.Run "WinWord" CloseDescendentProcesses: - It closes all applications which are opened by QTP Ex: -SystemUtil. CloseDescendentProcesses CloseProcessByName: - It closes the given Process Name Ex: -SystemUtil. CloseProcessByName ("EXCEL.EXE")
  • 41. Synchronization -->It is a process of matching the execution speeds for both application and QTP We can implement Synchronization in 4 ways 1. Wait() function 2. WaitProperty Method 3. Increase/ Decrease default time Setting 4. VB Scripting ** 1. Wait Function: --->By using this function we can make to QTP wait in given time in seconds -->It‟s a static way Limitations: - If given time is more than actual application time QTP still to wait, hence we have a performance issue. If given time is less than actual application time than QTP does not wait and continues to next step execution, hence we will get invalid results. Syntax: - Wait (Time in Seconds) Ex: - Wait (30) 2. WaitProperty Method: - ->By using this we can apply synchronization on required object. To wait QTP for given time in milliseconds. Syntax: - 3. Increase/ Decrease default Time Setting: - -->When ever QTP not able to perform any statement then it will wait up to given default time. Navigation: - File -->Setting -->Run -->Increase/ Decrease default time in object Synchronization time out field in seconds. 4. VB Script: - *** Example: - Obj. WinButton (“Insert Order”).Click While obj. WinButton (―Update Order‖).GetROProperty (―enabled‖) = ―False‖ Wend iOrdNo = obj.WinEdit (“Order No”). GetROProperty (“text”) MsgBox iOrdNo [To know the execution time of use MercuryTimers in Utility Objects] Example: -For Synchronization {for this we need Flight Reservation Application} Chapter IX Parameterization Parameterization: - It is a process of replacing static values with dynamic values and executing test scripts with multiple test data is called as parameterization. --> We maintain test data and passing it to UT through QTP in bellow ways. 1. Data Table 2. Environment Variable 3. External Files [Ms-Excel, Notepad, Ms-Word, XML] 4. Action Parameters QTP - Chapter X - XI Data Table Parametrization Chapter X Implementing parametrization by using Data Table Data Table: - It is used to hold the Test Date
  • 42. Navigation: - Data Table View Menu --> It is looks like MS-Excel Spread Sheet --> It contains 65536 Rows and 256 Columns --> By default it contains Global and Action1 Sheet --> Every action of the scripts contains the same sheet in the Data Table Types of Data Table: - 1. Design Data Table 2. Run Time Data Table Design Data Table: - Table which is displaying in test pane is called as Design Data Table Run Time Data Table: - The table which is displaying result window called as Runtime Data Table Note: - Run time Data Table is copy of Design Data Table Note: - Any modifications to data table during runtime it performs the operations in Run Time Data Table not in Design Data Table Note: -Test script execution iterations depends on Global Sheet number of Rows Example: - Global Action1 Action No. of Iterations - - - 1 - 5 10 1 5 10 15 5 10 5 1 10 Rename the column Names of Data Table: - Navigation: - Select the required sheet Design Data Table -->Double click on required column -->Enter new column name -->Click OK Button. By Scripting: - Syntax: - DataTable.GetSheet (“”).AddParameter””, “” Example: - Adding User_Name Column in Global Sheet DataTable.GetSheet(“Global”).AddParameter”User_Name”,”Sreekar” Example: - Adding Val1 Column in Action1 Sheet DataTable.GetSheet(“Action1”).AddParameter”Val1”,”Sreekar” ScriptNo17: - Write a script to find given sheet existence in data table sExpSht = "Action" iFlag = 0 iShtCnt = DataTable.GetSheetCount 'MsgBox iShtCnt For index = 1 To iShtCnt sActSht = DataTable.GetSheet(index).Name If sExpSht = sActSht Then Print "Sheet is Found" iFlag = 1 Exit For End If Next If iFlag = 0 Then Print "Sheet is not Found" End If
  • 43. Retrieving data From Data Table: - --> It retrieves from Run Time Data Table not from Design Table 1. MsgBox DataTable("User_Name") MsgBox DataTable("User_Name",1) MsgBox DataTable("User_Name","Global") MsgBox DataTable. Value("User_Name",1) -->It retrieves User_Name Column value from Global Sheet 2. MsgBox DataTable("User_Name","Action1") -->It retries User_Name Column Value from Action1 Sheet 3. MsgBox DataTable.GetSheet("Global").GetParameter("User_Name").ValueByRow(4) -->It retrieves 4th of User_Name column value from Global Sheet 4. MsgBox DataTable.GetSheet("Action1").GetParameter("User_Name").ValueByRow(4) -->It retrieves 4th row of User_Name column value from Action1 Sheet Entering Data into Data Table: - 1. DataTable("val","Global")="QTP" It Enters "QTP" in val column of Global Sheet 2. DataTable("val","Action1")="QTP" It Enters "QTP" in val column of Action1 Sheet 3. DataTable.GetSheet("Global").GetParameter("val").ValueByRow(3)="QTP" It Enters "QTP" in 3rd Row of val column in Global Sheet 4. DataTable.GetSheet("Action1").GetParameter("val").ValueByRow(3)="QTP" It Enters "QTP" in 3rd Row of val column in Action1Sheet Methods for Data Table: -By using this method we can perform required operations to the Run Time Data Table 1. AddSheet: - It is used to add a required sheet to the Run time Data Table (RDT) Syntax: - DataTable. AddSheet””
  • 44. Ex: - DataTable.AddSheet"MySheet" -->If we have data in multiple rows in Global Sheet then it over rights the sheet do not creates new sheet like MYSheet1 2. DeleteSheet: - It is used to Delete a required sheet from RDT Syntax: - DataTable. DeleteSheet"" Ex: DataTable.DeleteSheet"Global" DataTable.AddSheet"MySheet" DataTable.DeleteSheet"Action1" -->At least one is default in Data Table 3. Export: - It is used to save a RDT in given path Syntax: - DataTable.Export”Path” Ex: - DataTable.Export"E:01 My Scriptstest.xls" 4. ExportSheet: - It is used to Save a required sheet of RDT in required path Syntax: - DataTable.ExportSheet"Path",”” Ex: DataTable.AddSheet"MySheet" DataTable.GetSheet("MySheet").AddParameter"User_Name","Sreekar" DataTable.ExportSheet"E:01 My Scriptstest.xls","MySheet" 5. GetCurrentRow: - It is used to retrieve the current Active Row from the required sheet of RDT. Ex: - --> Retrieving from Global Sheet MsgBox DataTable.GetCurrentRow (or) MsgBox DataTable.GetSheet("Global").GetCurrentRow Retrieving from Action1 Sheet MsgBox DataTable.GetSheet("Action1").GetCurrentRow 6. GetRowCount: - By using this we can retrieve number of rows from required sheet of RDT Ex: -->Retrieving from Global Sheet MsgBox DataTable.GetRowCount (or) MsgBox DataTable.GetSheet("Global").GetRowCount -->Retrieving from Action1 Sheet MsgBox DataTable.GetSheet("Action1").GetRowCount 7. GetSheet: - It is used to Activate required sheet from RDT Syntax: - DataTable.GetSheet("") Example: -DataTable.GetSheet("Global") DataTable.GetSheet("Action1") 8. GetSheetCount: - It is used to retrieve number of sheets from RDT Ex: - MsgBox DataTable.GetSheetCount 9. Import: - It is used to save a excel file in RDT [How many sheets we have in RDT it imports only that number of sheets from Excel] Ex: - DataTable.AddSheet"MySheet" DataTable.Import"E:01 My Scriptstest.xls"
  • 45. 10. ImportSheet: - It is used to save a required sheet of MS-Excel to required sheet of RDT Syntax: - DataTable.ImportSheet”Path”,Ms-Excle Sheet ID, RDT Sheet ID Ex: - DataTable.ImportSheet"E:01 My Scriptstest.xls",3,2 11. SetCurrentRow: - It is used to activate required row in required sheet of RDT Ex: - -->Activating row in Global Sheet DataTable.SetCurrentRow(1) [or] DataTable.GetSheet ("Global").SetCurrentRow(2) -->Activating row in Action1Sheet DataTable.GetSheet ("Action1").SetCurrentRow(2) 12. SetNextRow: - It activates the Next row of current active row Ex: ---> Activating Global Sheet DataTable. SetNextRow (or) DataTable.GetSheet("Global").SetNextRow -->Activating Action1 Sheet DataTable.GetSheet("Action1").SetNextRow 13. SetPrevRow: -It activates previous row of current active row Ex: - -->Activating Global Sheet DataTable. SetPrevRow DataTable.GetSheet("Global").SetPrevRow -->Activating Action1 Sheet DataTable.GetSheet("Action1").SetPrevRow Ex: - MsgBox DataTable. GetCurrentRow DataTable.GetSheet ("Action1").SetPrevRow DataTable ("val1","Action1") ScriptNo18: - Write a script to find mathematical operation to given values, maintain data in Excel File. On Error Resume Next Dim iRowCnt,iRowNum,iVal1,iVal2 DataTable.ImportSheet"E:01 My Scriptscal.xls", 1, 2 iRowCnt = DataTable.GetSheet("Action1").GetRowCount For iRowNum = 1 To iRowCnt iVal1 = CInt (DataTable("val1","Action1")) iVal2 = CInt (DataTable("val2","Action1")) DataTable("add","Action1") = iVal1 + iVal2 DataTable("sub","Action1") = iVal1 - iVal2 DataTable("mul","Action1") = iVal1 * iVal2 DataTable("div","Action1") = iVal1 / iVal2
  • 46. If Err.Number <> 0 Then DataTable("comments","Action1") = Err.Description Err.Clear End If DataTable.GetSheet("Action1").SetNextRow Next DataTable.Export"E:01 My Scriptscalresult.xls" ScriptNo19: - Write a script for Login functionality for Multiple Users -->Maintain DATA in MS-Excel DataTable.ImportSheet"E:01 My Scriptsdatatable-user.xls",1,2 iRowCnt = DataTable.GetSheet("Action1").GetRowCount For i = 1 To iRowCnt sUname = DataTable("Username","Action1") sPwd = DataTable("Password","Action1") SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set sUname Dialog("Login").WinEdit("Password:").Set sPwd Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then Dialog("Login").Dialog("Flight Reservations").Activate sError = Dialog("Login").Dialog("Flight Reservations").Static("Please enter agent name").GetROProperty("text") Dialog("Login").Dialog("Flight Reservations").Close Dialog("Login").Close DataTable("Results","Action1") = sError Else If Window("Flight Reservation").Exist Then DataTable("Results","Action1") = "Valid User" Window("Flight Reservation").Activate Window("Flight Reservation").Close Else DataTable("Results","Action1") = "User is valid but not opened the application" End If End If Else DataTable("Results","Action1") = "Application not Oppened"
  • 47. End If DataTable.GetSheet("Action1").SetNextRow Next DataTable.Export"E:01 My Scriptsdatatable-user1.xls" ScriptNo20: - Write a script to retrieve Fly From dropdown values [Maintain in Excel] ScriptNo21: - Write a script to import Val1 values from sample1.xls file and import Val2 values from sample2.xls file, perform the mathematical operations and write the result in results.xls file QTP - Chapter XI Parameterization Environment Variable Implementing parameterization by using Environment Variable By using Environment Variables we can share the variable values in multiple actions (or) multiple scripts Types of Environment Variables: - 1. Built-In Environment Variables 2. User Defined Internal Environment Variables 3. User Defined External Environment Variables Built-In: - These are Pre-Defined by QTP Navigation: - Select Variable Type as Built-In Environment Setting File Menu Ex: - ActionName: Retrieves current action name ResultDir: Retrieves Test Script execution Result Path TestName: Retrieves Current Test Script Name MsgBox Environment ("ActionName") MsgBox Environment ("ResultDir") MsgBox Environment ("TestName") Note 1: - Built-In Environment variables are Read-Only Note 2: - Environment Variables are case sensitive User Defined Internal: - Declaring and using in same test scripts are called as User Defined Internal Environment Variables Navigation: - File Menu-->Environment Setting-->Select Variable Type as User Defined-->Click on ADD[+] Button Enter name and Value-->Click OK button -->Click Apply and OK Note: - Internal Environment variables are not Read-Only we can modify data at run time. Syntax: - Environment(“”) = “” Environment(“iVal”) = 10
  • 48. User Defined External: - Creating external Environment Variables: - Method 1: By Navigation: - File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on ADD [+] Button Enter Name and Value-->click on OK button-->click Export Button-->Save the file in required path with “.XML” extension Method 2: Open NOTEPAD and declare the variables as follows sPassword mercury sUserName suresh Associating External Environment Variable File:- Method 1: Navigation: - File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on Load Variables and Values from Eternal File Check Box-->Browse XML file-->Click Apply and OK buttons Method 2: - Syntax: - Environment.LoadFromFile”File Path” Environment.LoadFromFile "E:01 My Scriptsexternal EV.xml" Note: - We can associate only one XML file by navigation OR by scripting if we associate 2nd file then first file will be replaced with second file. Note: - User Defined External Environment Variable are Read Only.. QTP - Chapter XII External File [Excel] Parameterization Implementing parameterization by using External File External files are the files where we maintain the data outside of QTP, like ms-Excel, Notepad, Ms-Word, XML… Working with MS-EXCEL Creating Excel Object: - Set objXL = CreateObject("Excel.Application") Creating Work Book Object: - Set objWrkBk = objXL.Workbooks.Add Open an Existing Work Book: - Set objWrkBk = objXL.Workbooks.Open("E:01 My Scriptsexternal EV.xml") Creating a Work Sheet Object: - Set objWrkSht = objWrkBk.Worksheets("Sheet1") 'Activating the Sheet Find the No. of Rows: - MsgBox objWrkSht.UsedRange.Rows.Count Find the No. of Columns:- MsgBox objWrkSht.UsedRange.Columns.Count Retrieving a required Cell Value: - MsgBox objWrkSht.Cell(3,2) Entering data to Cell: - objWrkSht.Cell(14,8) = "QTP" Save opened Work Book: - objWrkBk.Save Save the New Work Book: - objWrkBk.SaveAs"Path" Close the Work Book: - objWrkBk.Close Close Excel: - objXL.Quit Kill Excel Process: - Set objWrkSht = Nothing
  • 49. Set objWrkBk = Nothing Set objXL = Nothing External File [Excel] ScriptNo22: - Write a script to create orders maintain data in Excel file 'Option Explicit 'Dim objXL,objWrkBk,objWrkSht,iRowCnt Set objXL = CreateObject("Excel.Application") Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel.xls") Set objWrkSht = objWrkBk.Worksheets("Sheet1") iRowCnt = objWrkSht.UsedRange.Rows.Count Set obj = Window("Flight Reservation") For index = 2 To iRowCnt obj.Activate obj.WinMenu("Menu").Select "File;New Order" dDate = objWrkSht.Cells(index,1) '(Row,Column) obj.WinObject("Date of Flight:").Type dDate sFrom = objWrkSht.Cells(index,2) obj.WinComboBox("Fly From:").Select sFrom sTo = objWrkSht.Cells(index,3) obj.WinComboBox("Fly To:").Select sTo obj.WinButton("FLIGHT").Click obj.Dialog("Flights Table").WinList("From").Select(0) obj.Dialog("Flights Table").WinButton("OK").Click sName = objWrkSht.Cells(index,4) obj.WinEdit("Name:").Set sName sCls = objWrkSht.Cells(index,5) obj.WinRadioButton(sCls).Set iTckts = objWrkSht.Cells(index,6) obj.WinEdit("Tickets:").Set iTckts obj.WinButton("Insert Order").Click While obj.WinButton("Update Order").GetROProperty("Enabled") = "False" Wend iOrdNo = obj.WinEdit("Order No:").GetROProperty("Text") If IsEmpty(iOrdNo) = "False" Then objWrkSht.Cells(index,7) = obj.WinEdit("Price:").GetROProperty("Text") objWrkSht.Cells(index,8) = obj.WinEdit("Total:").GetROProperty("Text") objWrkSht.Cells(index,9) = obj.WinEdit("Order No:").GetROProperty("Text") objWrkSht.Cells(index,10) = "Order is Generated"
  • 50. Else objWrkSht.Cells(index,10) = "Order is Not Generated" End If Next objWrkBk.Save objWrkBk.Close objXL.Quit Set objWrkSht = Nothing Set objWrkBk = Nothing Set objXL = Nothing Renaming a Sheet Name: - Set objXL = CreateObject ("Excel.Application") Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel1.xlsx") Set objWrkSht = objWrkBk.Worksheets("Sheet2") objWrkSht.Name = "User_Data1" Add a New sheet to Workbook: - objWrkBk.Sheets.Add Delete an Existence Sheet: - objWrkBk.Sheets("Sheet3").Select objXL.ActiveWindow.SelectedSheets.Delete Auto fit for require Column in Active Sheet: - objWrkSht.Columns("D:D").EntireColumn.AutoFit Wrap Text {Format Column}: - 'objWrkSht.Columns("A1:D1").HorizontalAlignment = xlGeneral 'objWrkSht.Columns("A1:D1").VerticalAlignment = xlTop objWrkSht.Columns("A1:D1").WrapText = True Bold and Color to one Cell: - objWrkSht.Cells(8,8).Font.Bold = True objWrkSht.Cells(8,8).Font.Color = vbRed objWrkSht.Cells(8,8) = "Suresh" objWrkSht.Cells(8,8).Interior.ColorIndex = 55 ScriptNo23: - Write a script to retrieve val1 values from sheet1, retrieve val2 values from sheet2 and perform mathematical operation and retrieve the results in sheet3
  • 51. Working with NOTEPAD Creating notepad Object: - Set objFile = CreateObject ("Scripting.FileSystemObject") Creating Notepad Pointer: - Syntax: -Set objPtr = objFile. OpenTextFile (“Path of Notepad”,Mode[,True]) Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1) Retrieving Value from notepad: - Retrieving a Line: objPtr.ReadLine Retrieving all Values: objPtr.ReadAll Retrieving One by One on till end of Line: While objPtr.AtEndOfLine = "False" MsgBox objPtr.SkipLine 'Even MsgBox objPtr.ReadLine MsgBox objPtr.SkipLine 'Odd Wend Retrieving given Line value: -
  • 52. Set objFile = CreateObject ("Scripting.FileSystemObject") Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1) iLine = 1 iFlag = 0 While objPtr.AtEndOfLine = "False" If iLine = 5 Then MsgBox objPtr.ReadLine iFlag = 1 Else ival1 = objPtr.ReadLine End If iLine = iLine + 1 Wend If iFlag= 0 Then MsgBox "Line number not found" End If Entering the Data/values into notepad: - Set objFile = CreateObject("Scripting.fileSystemObject") Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2,True ) objPtr.write "Suresh" objPtr.WriteLine "Sreekar" objPtr.WriteLine"Prsad" objPtr.WriteLine "Srilatha" objPtr.Write "Sushma" objPtr.WriteLine"Subashini" objPtr.Write"Sandeep" objPtr.Write"Sanjay" Notepad Object Method: - 1. CopyFile 2. CopyFolder 3. CreateFolder 4. CreateTextFile 5. DeleteFile 6. DeleteFolder 7. FileExists 8. FolderExists 9. OpenTextFile CopyFile: - Copy one file content to another file of same file types Syntax: - objFile.CopyFile"path of source file","path of destination file" Ex: - objFile.CopyFile" D:sample1.txt ","D: sample2.txt" CopyFolder: - Copy one file content to another file of same file types Syntax: - objFile.CopyFolder"path of source file","path of destination file" CreateFolder: - It is used to create a required folder in required path Syntax: -objFile.CreateFolder”path” Ex: - objFile.CreateFolder”d:test datasample” Creating a Folder with Current System data & time: Set objFile = CreateObject("Scripting.FileSystemObject")
  • 53. iFoldername = Now iFoldername = Replace(iFoldername,"/","_") iFoldername = Replace(iFoldername,":","_") objFile.CreateFolder "E:01 My Scripts"&iFoldername CreateTextFile: - By using this method we can create new Notepad File Ex: - Set objFile = CreateObject("Scripting.fileSystemObject") objFile.CreateTextFile("E:01 My ScriptsSample3.txt") DeleteFile: - Used to delete existing file DeleteFolder: - Used to delete existing Folder FileExists: - By using this method we can find file exist: It returns True if file exist It returns False if file exist Ex: - MsgBox objFile.FileExists("E:01 My ScriptsSample3.txt") FolderExists: - By using this method we can find Folder exist: It returns True if file exist It returns False if file exist Ex: - MsgBox objFile.FolderExists("E:01 My Scripts") OpenTextFile: - It is used to open exist text file for read/write/ append Ex: - Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2) ScriptNo24: - Write a script to copy sample excel data into Notepad Set objFile = CreateObject("Scripting.fileSystemObject") Set objPtr = objFile.OpenTextFile("E:01 My Scripts3.txt",2,True) Set objXl = CreateObject("Excel.Application") Set objWrkBk = objXl.Workbooks.Open("E:01 My ScriptsExp.xlsx") Set objWrkSht = objWrkBk.Worksheets("Sheet1") iRowCnt = objWrkSht.UsedRange.Rows.Count For iRowNum = 2 To iRowCnt sName = objWrkSht.Cells(iRowNum,1) iExperience = objWrkSht.Cells(iRowNum,2) sIndustry = objWrkSht.Cells(iRowNum,3) objPtr.WriteLine sName&" has "&iExperience&" Years of Experience in "&sIndustry&" industry” Next objWrkBk.Close Set objWrkSht = Nothing Set objWrkBk = Nothing Set objXl = Nothing Set objPtr = Nothing Set objFile = Nothing ScriptNo25: - Write a script for Fax Order; maintain fax numbers in notepad file Set objFile = CreateObject("Scripting.FileSystemObject") Set objPtr1 = objFile.OpenTextFile("E:01 My Scripts2.txt",1) Set objPtr2 = objFile.OpenTextFile("E:01 My Scripts4.txt",2,True) Set obj = Window("Flight Reservation") While objPtr1.AtEndOfLine = "False" sStr = objPtr1.ReadLine
  • 54. sString = Split(sStr," ") iOrderNo = sString(3) iFaxNo = sString(8) 'MsgBox iOrderNo &" " &iFaxNo obj.Activate obj.WinMenu("Menu").Select "File;Open Order..." obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON" obj.Dialog("Open Order").WinEdit("Edit_2").Set iOrderNo obj.Dialog("Open Order").WinButton("OK").Click If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(4) Then obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Open Order").WinButton("Cancel").Click objPtr2.WriteLine iOrderNo &"Order is not found and hence unable to send Fax" Else obj.Activate obj.WinMenu("Menu").Select "File;Fax Order..." obj.Dialog("Fax Order No. 1").WinObject("Fax Number:").Type iFaxNo obj.Window("Fax Order No. 1").RunAnalog "Track1" obj.Dialog("Fax Order No. 1").WinButton("Send").Click If obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").Exist(4) Then obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Fax Order No. 1").WinButton("Cancel").Click objPtr2.WriteLine "Invalid Fax Number" &iFaxNo& "For the Order" &iOrderNo Else While obj.Dialog("Fax Order No. 1").Exist(2) = True Wend sFaxMsg = obj.WinObject("Fax Sent Successfully...").GetROProperty("Text") If sFaxMsg = "Fax Sent Successfully..." Then objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo Else objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo End If End If End If Wend Note: - Generally we use Notepad for maintaining DATABASE queries Note: - For general maintaining data like UserName, Password…etc we use excel files Working with Ms-Word Set objWrd = CreateObject(“Word.Application”) Creating XML object
  • 55. Set objXML = CreateObject(“XML.Application”) Implementing parameterization by using Action Parameters -->Actions are used to divide test script in to logically related groups of QTP statements. -->Actions are used to script maintainability and script re-usability. --> We use actions when functional testers maintain scenario based test scripts. That is one scenario containing multiple test cases. Ex: - Scenario -->Every script we have “default action”, it is Action1 -->Every action of script will have sheet in data table and sheet name will be same as Action name. Creating a New Action: - Method-1:- By Navigation: - Click OK Button Enter Action Name Call to New Action Insert Menu Method-2:- Run Time: - Set objQtp = CreateObject(“QuickTest.Application”) objQtp.Test.AddNewAction””,””,” Content>”,””,”” Ex: - objQtp.Test.AddNewAction “sample”,”test”,”test”, 1, 1 ScriptNo26: - Write a script to create multiple Actions and prove that we can create only 255 actions
  • 56. QTP - Chapter XIII Re-Naming: - Select the required Action-->Right Click on Test Pane-->Actions-->Action Properties-->Re-Name the Action Name-->Click OK button. Deleting an Action: - Navigation1: -Select the required action-->Edit Menu-->Action-->Delete Action-->Click Yes Button in Conformation message. Navigation2: - Keyword view -->Right Click on required Action-->Select Delete-->Click Yes Button in conformation message. ScriptNo27: - Write a script to find given Action Existence sExpAction = "Action5" iFlag = 0 Set objQtp = CreateObject("QuickTest.Application") iActionCnt = objQtp.Test.Actions.Count MsgBox iActionCnt For index = 1 to iActionCnt Print objQtp.Test.Actions(index).Name If objQtp.Test.Actions (index).Name = sExpAction Then MsgBox "Action is Found" iFlag = 1 Exit for End If Next If iFlag = 0 Then MsgBox "Action is Not Found" End If Set objQtp = Nothing -->By default actions are executing in order which we are created. -->If we want to change the order of action execution then we follow bellow navigation Navigation: - Select the required action and drag and drop in required position Keyword View Types of Actions: - 1. Normal /Non Reusable Action
  • 57. 2. Re- Usable Actions 3. External Re-Usable Actions Normal /Non Reusable Action: - An Action that can be called only in the test without reusability called as Normal /Non Reusable Action. Re- Usable Actions: - An Action that can be called in same test script and in another test script multiple times is called as Re- Usable Actions. External Re-Usable Actions: - An Action that can be call in same test script or in another test script in multiple times in READ ONLY mode are called as External Re-Usable Actions Implement Script Reusability by Action: - We can implement a Script Reusability by Action, in bellow ways 1. Call to Copy of Action 2. Call to Existing Action Calling Action: - The Action which is calling another action Called Action: - The Action which is called by another Action Implementing re usability by using Call to Copy: - Navigation: - Open calling test script -->insert Menu --> select call to copy of action -->browse the required called to test script -->select the required action --> click on OK button Syntax: - RunAction”Copy of ”, OneIteration Ex: - RunAction “Copy of login”, OneIteration RunAction “Copy of logout”, OneIteration Implementing re usability by using Call to Existing: - Navigation: - Open calling test script --> nsert Menu --> select call to Existing action-->browse the required called test script-->select the required action --> click on OK button Syntax: - RunAction “[Called Test Script]”, OneIteration Ex: - RunAction “login[Action Demo]”, OneIteration RunAction “logout[Action Demo]”, OneIteration Difference between call to Copy and Call to Existing: - Implementing Parameterization by using Action Parameters
  • 58. Action Parameters: - These are used to retrieving the data and sending results in between Called Action and Calling Action parameters. There are two types of action parameters 1. Input Parameters: - These are used to retrieving the data from Calling Action to Called Action 2. Output Parameters: - These are used to sending Test Result from Called Action to Calling Action Note: - We create Action Parameters in Called Action. Note: - Action Parameters are independent to Action Navigation to create Action Parameters: - Open Called test script-->select the required action right click on test pane-->select Action-->Action Properties-->select Parameter Tab-->Click Add button-->Enter parameter name and value-->Click on OK button. Split of Action: - Right click on required statement-->select Action-->Split-->Enter First Action Name--> Enter Second Action Name-->Click on OK button ScriptNo28: - Write a script for login logout by using Action Parameter Concept -->Open called Test Script and create 2 actions login and logout -->Enter bellow code -->Create sUname, sPwd input parameters and sRslt as output parameters Script Name [loginlogout]-Action Name [Login]: - [Add Action Parameters (sUName, sPwd, sRslt) to loginlogout script] SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Parameter("sUName") Wait(2) Dialog("Login").WinEdit("Password:").Set Parameter("sPwd") Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then Reporter.ReportEvent micFail,"Login Validation","Given Data is Invalid" Parameter("sRslt") = "Fail" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click Else If Window("Flight Reservation").Exist Then Reporter.ReportEvent micPass, "Login Validation","Login Validation is Pass" Parameter("sRslt") = "Pass" Window("Flight Reservation").Close Else Reporter.ReportEvent micFail, "Login Validation","Login Validation is Fail" Parameter("sRslt") = "Fail" End If End If End If
  • 59. Action Name [Logout]: - If Window("Flight Reservation").Exist(5) Then Window("Flight Reservation").Close While Window("Flight Reservation").Exist(2) = True Wend If Window("Flight Reservation").Exist(2) = "False" Then Reporter.ReportEvent micPass, "Close Application","Application is Closed" Else Reporter.ReportEvent micFail,"Close Application","Application is not Closed" End If End If [Here loginlogout script is called actions] Script Name [calngaction]: - this action is calling action Action Template: - It explains Action description as bellow ********************************************************************************* ACtion name: Action Description: Design Date: Tool Used: Comments: ********************************************************************************* Navigation: - Open notepad enter the action template save the file as “ActionTemplate.mst” [MST: -mercury scenario test script] in bellow path save it C:Program filesHPQuick Test Professionaldat
  • 60. Split of Action: - Right click on required statement-->select Action-->Enter First Action Name Split--> Enter Second Action Name-->Click on OK button ScriptNo29: -HW ActionDemo: - Action1 'MsgBox "Login" SystemUtil.Run "C:Program Files (x86)HPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate 'Msgbox Parameter("suname") 'MsgBox Parameter("spwd") Dialog("Login").WinEdit("Agent Name:").Set parameter("suname") Dialog("Login").WinEdit("Password:").Set Parameter("spwd") Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(3) Then Reporter.ReportEvent micFail, "Login Validation", "Invalid credentials " Parameter("srslt") = "Fail" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click Else Reporter.ReportEvent micPass , "Login Validation", "succesfully logged into flight reservation" Parameter("srslt") = "Pass" End If Else Reporter.ReportEvent micFail, "Login Validation", "Flight application is not opened" Parameter("srslt") = "Fail" End If Action2: - If Window("Flight Reservation").Exist Then Window("Flight Reservation").Close While Window("Flight Reservation").Exist(2) = True Wend If Window("Flight Reservation").Exist(3) = "False" Then Reporter.ReportEvent micPass, "Close Application", "Application is closed"
  • 61. Else Reporter.ReportEvent micFail,"close application","app is not closed" End If Else Reporter.ReportEvent micFail,"close app","app is not closed" End If New Order: - Open Order: -
  • 62. Fax Order: - 'Msgbox "Fax Order" Set objxl=CreateObject("Excel.Application") Set objwbk=objxl.Workbooks.Open ("D:Projectfaxorder.xls") Set objwst = objwbk.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8) iRcnt=objwst.UsedRange.Rows.count Set obj= window("Flight Reservation") If obj.Exist (5) Then For indx = 2 to iRcnt obj.Activate obj.WinMenu("Menu").Select "File;Open Order..." obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON" obj.Dialog("Open Order").WinEdit("Edit_2").Set objwst.Cells(indx,1) obj.Dialog("Open Order").WinButton("OK").Click If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(5) Then obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Open Order").WinButton("Cancel").Click Reporter.ReportEvent micFail,"Open Order","Order number doesnt exist" objwst.Cells(indx,3) = "order number doesnt exist" objptr.WriteLine Parameter("sUname") & " tried to open order number " & objwst.cells(indx,1) & " which doesnt exist" Else obj.Activate
  • 63. obj.WinMenu("Menu").Select "File;Fax Order..." obj.Dialog("Fax Order No. *.*").WinObject("Fax Number:").Type objwst.cells(indx,2) 'obj.Window("Fax Order No. *.*").RunAnalog "Track2" @@ hightlight id_;_3016516_;_script infofile_;_ZIP::ssf1.xml_;_ obj.Dialog("Fax Order No. *.*").WinButton("Send").Click If obj.Dialog("Fax Order No. *.*").Dialog("Flight Reservations").Exist(5) Then obj.Dialog("Fax Order No. *.*").Dialog("Flight Reservations").WinButton("OK").Click Reporter.ReportEvent micFail,"Send Fax","Not able to send fax" objwst.Cells(indx,3) = "Not able to send fax" objptr.WriteLine Parameter("sUname") & " tried to send fax to " & objwst.cells(indx,2) & " but not able to send fax" obj.Dialog("Fax Order No. *.*").WinButton("Cancel").Click Else While obj.Dialog("Fax Order No. *.*").Exist(3)="True" Wend sFaxMsg = obj.WinObject("AfxWnd40").GetROProperty("Text") If sFaxMsg = "Fax Sent Successfully..." Then Reporter.ReportEvent micPass,"Send Fax" , "Fax Sent Successfully" objptr.WriteLine Parameter("sUname") & " has successfully sent fax to " & objwst.cells(indx,2) objwst.Cells(indx,3) = "Fax sent successfully" End If End If End If Next Else Reporter.ReportEvent micFail,"Select Fax Order","Flight Reservation Window doesnot exist" End If objwbk.Save objwbk.Close objxl.Quit Set objwst = nothing Set objwbk = nothing Set objxl = nothing Set obj = nothing Set objptr = nothing Set objfile = nothing Delete order: - 'Msgbox "Delete order" Set objxl = CreateObject ("Excel.Application") Set objwb = objxl.Workbooks.Open("D:Projectdeleteorder.xls") Set objst = objwb.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8) Set obj = Window("Flight Reservation") iRcnt = objst.UsedRange.rows.count If obj.Exist(2)Then For indx = 2 to iRcnt sOnum = objst.cells(indx,1) If sOnum>10 Then
  • 64. RunAction "openord [openorder] [2]", oneIteration, sOnum, bOpen If bOpen Then Reporter.ReportEvent micPass,"Open Order","Opened the order to delete" If obj.WinButton("Delete Order").GetROProperty("Enabled")="True" Then obj.WinButton("Delete Order").Click If obj.Dialog("Flight Reservations").Exist Then obj.Dialog("Flight Reservations").WinButton("Yes").Click objst.cells(indx,2) = "Deleted order number "& sOnum objptr.WriteLine Parameter("sUname") & " has successfully deleted the order " & sOnum End If End If Else Reporter.ReportEvent micFail,"Delete Order","Order number doesnt exist" objst.cells(indx,2) =sOnum & " order number doesnt exist" objptr.WriteLine Parameter("sUname") & " tried to open order " & sOnum & " but order doesnt exist" End If Else Reporter.ReportEvent micFail,"Delete Order","Cannot delete orders below 10" objst.cells(indx,2) = "Cannot delete order number "& sOnum objptr.WriteLine Parameter("sUname") & " tried to delete order " & sOnum & " but cannot delete orders less than 10" End If Next End If objwb.Save objwb.Close objxl.Quit Set objst = nothing [ Set objwb = nothing Set objxl = nothing Set objptr = nothing Set objfile = nothing] Orders: - Set objxl = CreateObject ("Excel.Application") Set objwb = objxl.Workbooks.Open("D:Projectusers.xls") Set objst = objwb.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.CreateTextFile("D:ProjectFlightDetails.txt",8) ircnt = objst.UsedRange.Rows.Count For indx =2 to ircnt sUname = objst.cells(indx,1) sPwd = objst.cells(indx,2) RunAction "Login [ActionDemo] [2]", oneIteration, sUname, sPwd, Result Role = objst.cells(indx,3) Select Case Role Case "new order" RunAction "Action1 [neworder] [2]", oneIteration, iOrdno RunAction "Logout [ActionDemo] [2]", oneIteration objptr.WriteLine sUname & " has placed a new order generating order number: " & iOrdno objptr.Close Case "open order" RunAction "openord [openorder] [2]", oneIteration, iOrdno, bOpen RunAction "Logout [ActionDemo] [2]", oneIteration
  • 65. If objFile.FileExists("D:ProjectFlightDetails.txt") Then Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8) End If If bOpen Then objptr.WriteLine sUname & " has opened an existing order number: " & iOrdno Else objptr.WriteLine sUname & " has not opened an existing order number: " & iOrdno End If objptr.Close Case "Fax order" RunAction "faxorder [faxorder] [2]", oneIteration, sUname RunAction "Logout [ActionDemo] [2]", oneIteration Case "delete order" RunAction "delorder [deleteorder] [2]", oneIteration, sUname RunAction "Logout [ActionDemo] [2]", oneIteration Case Else End Select Next objwb.Save objwb.Close objxl.Quit Set objst = nothing [ Set objwb = nothing Set objxl = nothing Set objptr = nothing Set objfile = nothing] QTP - Chapter XIV - XV Functions --> Functions are used to script maintainability and reusability Types of Functions:- 1. QTP Built in Functions [VB Script Chapter] 2. User Defined Functions User Defined Functions: - Syntax: - [public/ private] Function ([Parameters]) [Exit Function] End Function Public: - Indicates that the function procedure is accessible to all other procedures in all scripts. Private: - Indicates that the function procedure is accessible only to other procedures in the script where it is declared / if the function is a member of a class, and that the function procedure is accessible only to the other procedures in that class. Function: - name of the function Parameters: - List of variables representing arguments that are passed to the function procedure when it is called Statement: - Any group of statements to be executed with in the body of the function procedure Exit Function: - It causes an immediate exit a function.
  • 66. Function Parameters: - Function parameters are used to retrieving the data from Calling Function to Called Function and sending result from Called Function to Calling Function. Types of Function Parameters: - 1. ByVal 2. ByRef Note: - We create function parameters in called function ByVal: - It retrieves data from calling function to called function Note*: - Any changes to ByVal it limits to the called function ByRef: - It retrieves data from calling function to called function and also sends test results from called function to calling function Note*: - Any changes to ByRef will be accessible inside the called function as well as calling function. Note*: - Default parameter type is ByRef Ex: - ScriptNo30: - Write a function to find given file existence MsgBox FileExist ("E:01 My Scripts1.txt") Function FileExist (sFilePath) Dim objFile
  • 67. Set objFile = CreateObject("Scripting.FileSystemObject") FileExist = objFile. FileExists (sFilePath) Set objFile = Nothing End Function ScriptNo31: - Write a script per calculating mathematical results per given values and operations. MsgBox Calculation (10,20,"+") MsgBox Calculation (10,20,"-") MsgBox Calculation (10,20,"*") MsgBox Calculation (10,20,"/") MsgBox Calculation (10,0,"/") MsgBox Calculation (10,"$","/") Function Calculation (iVal1,iVal2,sOperator) Select Case sOperator Case "+" Calculation = iVal1 + iVal2 Case "-" Calculation = iVal1 - iVal2 Case "*" Calculation = iVal1 * iVal2 Case "/" Calculation = iVal1 / iVal2 Case "/" Calculation = iVal1 / iVal2 Case "/" Calculation = iVal1 / iVal2 If Err.number <> 0 Then Calculation = Err.Description Err.Clear End If Case Else Calculation = "Invalid Operator" End Select End Function Library Files: - It contains all functions Creating Library File: - Method 1: -Open Notepad declare the functions and save the file with “.vbs” extension Method 2: -Start-->All Programs-->QTP-->Tools-->Quick Test Script Editor-->Click New Button-->Declare the Functions-->Save the File with “.qfl” extension Method 3: - QTP-->New Dropdown-->Select Function Library-->Declare the Functions-->Save the file with “.qfl” extension Associating Library Files: - After creating library files we need to associate a required test script By Navigation: - File Menu-->Setting-->Resources-->click on Add button-->Browse and open require library file vbs/ qfl -->Click on apply and ON. By Script:- Syntax: - ExecuteFile “Path of the library file” Ex: - ExecuteFile” E:01 My Scripts1.vbs” Difference between By Navigation and By Script
  • 68. Note: - If associate library file and execute a test script, QTP first executes library files and executes test script Note: - If we associate multiple library files it executes down to top Ex: - Sample1.vbs Sample2.vbs First it executes sample 2 then sample1 Note: - we can declare variables in library file [Global variable] RegisterUserFunc: - To define user defined methods by using functions. RegisterUserFunc "Activex","Set","Sample" Function Sample(obj,sString) Sample = obj.Type(sString) End Function Window ("Flight Reservation").ActiveX("MaskEdBox").Set("121213") ScriptNo32: - Write a library file for OMBS_Login, Create a Bank, Delete a Bank, OMBS_Logout OMBS_Library: - ******************************************************************************** 'Function Name : OMBS_Login 'Function Description: This function validates OMBS login 'Parameters : User name, password and User Type 'Return Value: True / False 'Design Date: 02/14/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments: ******************************************************************************** Function OMBS_Login(sUsrName,sPwd,sUsrType) SystemUtil.Run "iexplore","http://192.168.1.50:8050/unifi/" Set obj=Browser("OnlineNetBanking").Page("OnlineNetBanking") If obj.Exist Then Reporter.ReportEvent micPass,"Open OMBS application","OMBS application is opened" obj.WebEdit("UserName").Set sUsrName obj.WebEdit("Password").SetSecure sPwd sAllItems=obj.WebList("UserType").GetROProperty("all items") If InStr(sAllItems,sUsrType)>0 Then obj.WebList("UserType").Select sUsrType obj.WebButton("Submit").Click If Browser("WelcomePage").Page("WelcomePage").Image("Back").Exist(5) Then Reporter.ReportEvent micFail,"Enter user deatils and click on Submit button","Given user credentials are invalid" OMBS_Login=False SystemUtil.CloseDescendentProcesses Else Reporter.ReportEvent micPass,"Enter user deatils and click on Submit button","Welcome page is opened" OMBS_Login=True End If
  • 69. Else Reporter.ReportEvent micFail,"Select User type",sUsrType&" item is not found in User type dropdown" OMBS_Login=False SystemUtil.CloseDescendentProcesses End If Else Reporter.ReportEvent micFail,"Open OMBS application","OMBS application is not opened" OMBS_Login=False SystemUtil.CloseDescendentProcesses End If End Function ********************************************************************************* 'Function Name : OMBS_Logout 'Function Description: This function validates OMBS Logout 'Parameters : N/A 'Return Value: True / False 'Design Date: 02/14/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments: '********************************************************************************* Function OMBS_Logout() If Browser("WelcomePage").Page("WelcomePage").Exist Then Browser("WelcomePage").Close While Browser("WelcomePage").Exist(2)=True Wend If Not Browser("WelcomePage").Exist(2) Then Reporter.ReportEvent micPass,"Close application","Application is closed" OMBS_Logout=True Else Reporter.ReportEvent micFail,"Close application","Application is not closed" OMBS_Logout=False SystemUtil.CloseDescendentProcesses End If Else Reporter.ReportEvent micFail,"Click Logout link","Logout link not found" OMBS_Logout=False SystemUtil.CloseDescendentProcesses End If End Function '************************************************************************** 'Function Name: OMBS_CreateBank 'Function Description: This function validates Create Bank functionality „Parameters: sBankId,sBankName,sAddr,iPhone,sLoc 'Return Value: True / False 'Design Date: 02/15/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments:
  • 70. '************************************************************************** Note***: - Where we unable to identify objects with Object Spy we have a “ClickOnText”. Function OMBS_CreateBank(sBankId,sBankName,sAddr,iPhone,sLoc) Set obj=Browser("WelcomePage").Page("WelcomePage") If obj.Exist Then Reporter.ReportEvent micPass,"Validate Welcome page is opened”, “Welcome page is opened" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Banks Database" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "New Banks" If obj.Frame("Main").WebButton("AddNew").Exist Then Reporter.ReportEvent micPass,"Click New Banks link","New bank Entry page is opened" obj.Frame("Main").WebButton("AddNew").Click obj.Frame("Main").WebEdit("BankId").Set sBankId obj.Frame("Main").WebEdit("Name").Set sBankName obj.Frame("Main").WebEdit("Addres").Set sAddr obj.Frame("Main").WebEdit("PhoneNo").Set iPhone obj.Frame("Main").WebEdit("Location").Set sLoc obj.Frame("Main").WebButton("Submit").Click If obj.Frame("Main").WebElement("BankDatabaseEntrySucceded").Exist Then Reporter.ReportEvent micPass,"Enter bank details and click on Submit button","New bank is created" OMBS_CreateBank=True Else Reporter.ReportEvent micFail,"Enter bank details and click on Submit button","New bank is not created" OMBS_CreateBank=False End If obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Banks Database" Else Reporter.ReportEvent micFail,"Click New Banks link","New bank Entry page is not opened" OMBS_CreateBank=False End If Else Reporter.ReportEvent micFail,"Create Bank","Welcome page is not opened" OMBS_CreateBank=False End If End Function '************************************************************************** 'Function Name: OMBS_DeleteBank 'Function Description: This function validates Delete Bank functionality „Parameters: sBankId 'Return Value: True / False 'Design Date: 02/15/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments: '************************************************************************** Function OMBS_DeleteBank(sBankId) Dim obj,sItems Set obj=Browser("WelcomePage").Page("WelcomePage") If obj.Exist Then
  • 71. Reporter.ReportEvent micPass,"Delete Bank","Welcome page is opened" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Banks Database" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Delete Banks" If obj.Frame("Main").WebButton("DeleteSubmit").Exist Then Reporter.ReportEvent micPass,"Click on Delete banks link","Delete bank page is opened" sItems=obj.Frame("Main").WebList("BankId").GetROProperty("All Items") If InStr(sItems,sBankId)>0 Then obj.Frame("Main").WebList("BankId").Select sBankId obj.Frame("Main").WebButton("DeleteSubmit").Click obj.Frame("Main").WebButton("Delete").Click If obj.Frame("Main").WebElement("YourBanksDeletedSucceeded").Exist Then Reporter.ReportEvent micPass,"Delete bank","Bank is deleted" OMBS_DeleteBank=True End If End Function '************************************************************************** 'Function Name: OMBS_DeleteBank 'Function Description: This function validates Delete Bank functionality „Parameters: sBankId 'Return Value: True / False 'Design Date: 02/15/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments: '************************************************************************** Function OMBS_DeleteBank(sBankId) Dim obj,sItems Set obj=Browser("WelcomePage").Page("WelcomePage") If obj.Exist Then Reporter.ReportEvent micPass,"Delete Bank","Welcome page is opened" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Banks Database" obj.Frame("Contents").ActiveX("MenuList").ClickOnText "Delete Banks" If obj.Frame("Main").WebButton("DeleteSubmit").Exist Then Reporter.ReportEvent micPass,"Click on Delete banks link","Delete bank page is opened" sItems=obj.Frame("Main").WebList("BankId").GetROProperty("All Items") If InStr(sItems,sBankId)>0 Then obj.Frame("Main").WebList("BankId").Select sBankId obj.Frame("Main").WebButton("DeleteSubmit").Click obj.Frame("Main").WebButton("Delete").Click If obj.Frame("Main").WebElement("YourBanksDeletedSucceeded").Exist Then Reporter.ReportEvent micPass,"Delete bank","Bank is deleted" OMBS_DeleteBank=True TC1_LoginLogut: - [Script for OMBS library] '************************************************************************** 'Test Name : Login and Logout 'Test Description: 'Design Date: 02/14/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments:
  • 72. '************************************************************************** If OMBS_Login("admin","511c647fd6c24ad6a136c42a4164f453","Administrator") Then Call OMBS_Logout() End If TC2_CreateBank_DeleteBank: - [Script for OMBS library] '************************************************************************** 'Test Name: Create and Delete bank 'Test Description: 'Design Date: 02/15/2013 'Author: Sreekar 'Tool used : QTP 10 'Comments: '************************************************************************** If OMBS_Login("admin","511db8845bb8f06fba66629e40b7edda","Administrator") Then If OMBS_CreateBank("push1234","push1234","test","1234567890","test") Then Call OMBS_DeleteBank("push1234") End If Call OMBS_Logout() End If QTP - Chapter XV Batch Testing and Debugging Batch Testing: - -->It is a process of executing multiple test scripts in a single execution -->We can implement batch testing in below ways: 1. By using Test Batch Runner Tool 2. By using Driver Script Test Batch Runner Tool: - It is inbuilt tool in QTP Prerequisite in QTP: - Tools-->Options-->Run-->Check allow other HP product to Run Test and Components Check Box Navigation: - Start-->All Program--> QuickTest Professional-->Tools--> Test Batch Runner-->Click Add Button-->Browse and Select require Scripts-->Save the script with .mtb [Mercury Test Batch] extension -->Click Run. Limitation: - unable to execute partial script, that is required actions in required scripts unable to execute Driver Script: - Executing Required Action: - Syntax: - LoadAndRunAction “Test Script Path and Name”, “Action Name” Ex: - LoadAndRunAction “E:01 My ScriptsBatch40”, “Action1” Example: - For this example create sample1 and sample2 scripts with actions
  • 73. --> Save above file as RunManager.xls in Preferred location --> Save the below script as DriverScript in required path DriverScript.mts: - Set objXL = CreateObject ("Excel.Application") Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsBatch40") Set objWrkSht = objWrkBk.Worksheets("Sheet1") iRowCnt = objWrkSht.UsedRange.Rows.Count For index = 2 to iRowCnt bStatus = UCase(objWrkSht.Cells(index,3)) If bStatus = "YES" Then sScript = objWrkSht.Cells(index,1) sAction = objWrkSht.Cells(index,2) LoadAndRunAction sScript, sAction End If Next objWrkBk.Close objXL.Quit Set objWrkSht = Nothing Set objWrkBk = Nothing Set objXL = Nothing InitScript.vbs: - Set objQTP = CreateObject ("QuickTest.Application") objQTP. Launch objQTP. Visible = True objQTP. Open "E:01 My ScriptsBatch40DriverScript.mts" objQTP. Test. Run objQTP. Quit Set objQTP = Nothing. Debugging: - After the scripts are developed to make sure that the scripts are correct and we need to debug the script. Scripts can have Two Types of Errors: - 1. Syntactical Error 2. Logical Error Syntactical Errors can be identified by Running Scripts or Saving Script and verify in Information Pane. Logical Error we need to apply debug options. Debugging is a process of executing the test script in user defined fashion/ way with some temporary break in order, to identify the error. To do the same, QTP has provided below debug options.
  • 74. Step Commands: - a. Step Into (F11): - It is used for executing a single step. If that step is a function call or action call then, it will step in to the function or action b. Step Out (Shift+F11): - It is used to executing all the remaining statements from the position of the pointer in a function or an action and steps out of the function or an action. c. Step Over (F10): - It is used for executing a single step. If that step is a function call or an action call then, it will execute the complete block of statements in that function or an action and steps out of that function or an action. Break Point (F9): - It is a feature by QTP, which is used for breaking the execution temporally ExitTest: - It is used to terminate the current script execution. ExitRun: - It is used to terminate the Batch process ExitAction: - It is used to terminate the current Action execution. Run from Step (Ctrl+F5): - It is used to execute from required step Navigation: - Place the pointer in required line-->right click and select Run from Step (or) Press Ctrl + F5 Debug from Step: - It is used to debug from required step Navigation: - Place the pointer in required line-->Right Click and select debug from step Run Current Action: - It is used to execute a required Action Navigation: - Select required action-->Automation menu -->Run Current Action. QTP - Chapter XVI - XVII Descriptive Programming Descriptive programming provides a means to perform interaction with runtime objects which are not in the Object Repository. The technique also proves, useful while developing test cases for applications which are not yet available for working with objects. When to use Descriptive Programming: - Below are some of the examples when descriptive programming is considered a good alternative to using a traditional object repository to define a test object. 1. When the objects in the application are dynamic in nature and need special handling to identify them at run time Example: - Clicking an object which changes according to the user navigation of the application. 2. When Object Repository is getting very large. If the size of OR increases too much then it decreases the performance of QTP during runtime 3. When we do not want to use an OR at all. 4. When modification to an OR object is required, but the object repository in which the object is read only or it is located in a shared OR and the changes may affect other scripts outside of our control. 5. When we want to take action on large number of similar/ uniform objects. For example we have 30 text boxes on a page and their names are in form of txt_1, txt_2… txt_30. In this situation adding 30 entries to OR would not be a good programming approach but using dynamically defined DP statements would be.
  • 75. We can implement Descriptive Programming in below Approaches: - 1. By Using Description Objects (Dynamic) 2. By Using Description String (Static) By Using Description Objects: - In this approach we create a description object and defined the properties and values for recognizing the objects by QTP. Description Objects: - Creating a user defined object without any properties. Creating Description Object: - Set = Description.Create Assigning properties and Values: - ObjName(“”).Value = “” Example: - Set objDlg(“text”).Value = “Login” Kill the object Process: - Set objName = Nothing ScriptNo33: - Write a descriptive programming for login by using description objects approach. By Using Description String: - In this approach of description programming we don‟t need to create a description object, instead we use Description String to recognize the objects. It means that we are maintaining object properties and their values in script itself. Description String: - It is a property name and its value Ex: - Dialog (“text: =Login”).WinButton (“text: =OK”).Click
  • 76. ScriptNo34: - Write a descriptive programming for login by using Description String approach Activating a Browser: - iHwnd = Browser ("Gmail").GetROProperty("hwnd") Window ("hwnd: ="&iHwnd).Activate OR ihwnd = Browser("name:=Google").GetROProperty("hwnd") Window("hwnd:="&ihwnd ).Activate MsgBox ihwnd ScriptNo35: - Write a Descriptive Programming to create New Order ScriptNo36: - Write a Descriptive Programming for g-mail. SystemUtil.Run"iexplore","www.gmail.com" Set obj = Browser ("name:= Gmail: Email from Google").Page("title:= Gmail: Email from Google")
  • 77. If obj.Exist Then obj.WebEdit("name:=Email").Set "abc@gmail.com" obj.WebEdit("name:=Passwd").Set "password" obj.WebButton("name:=signIn").Click If Browser ("Name:= Microsoft Internet Explorer").page("title:= Gmail - Inbox").Link("innerText:=Sign out").Exist Then Reporter.ReportEvent micPass,"Login Validation","Logon validation Pass" Browser ("Name:= Microsoft Internet Explorer").page("title:= Gmail - Inbox").Link("innerText:=Sign out").Click Browser ("Name:= Microsoft Internet Explorer").Close Else Reporter.ReportEvent micFail,"Login Validation","Logon validation Fail" End If End If Set obj = Nothing ScriptNo37: - Write a script to find number of buttons in Flight Reservation Window Set obj = Window ("Flight Reservation") Set objBtn = Description.Create objBtn("Class Name").Value = "WinButton" Set objLst = obj.ChildObjects (objBtn) MsgBox objLst. Count For index = 0 To objLst.Count -1 MsgBox objLst(index).GetROProperty("text") Next Set objBtn = Nothing Set objLst = Nothing Set obj = Nothing ScriptNo38: - Write a script to retrieve WinButton, WinComboBox, WinList, WinEdit, WinRadioButton in Flight Reservation window and write in excel file. ScriptNo39: - Write a script to retrieve all names in a page Set objlnk = Description.Create objlnk("micClass").Value = "Link" Set objlst = Browser("Google").Page("Google").ChildObjects(objlnk) MsgBox objlst. Count For index = 0 To objlst.Count-1 MsgBox objlst(index).GetROProperty("name") Next ScriptNo40: - Write a script to find number of browsers in desktop Set objBrowser = Description.Create objBrowser("application version").Value = "Internet explorer 7" Set objLst = Desktop.ChildObjects(objBrowser) MsgBox objLst.Count For index = 0 To objLst.Count-1 MsgBox objLst(index).GetRoProperty("name")
  • 78. Next Set objBrowser = Nothing ScriptNo41: - Write a script to close all the browsers except required browser [like QC…] Set objBrowser = Description.Create objBrowser("application version").Value = "Internet explorer 7" Set objLst = Desktop.ChildObjects(objBrowser) For index = 0 To objLst.Count-1 If objLst(index).GetRoProperty("Name")<>"Goolge" Then objLst(index).Close End If Next Set objLst = Nothing Set objBrowser = Nothing ________________________________________________________________________ Chapter XVII Regular Expression Regular Expressions are strings containing Special Meta characters used to, match patterns inside the scripting. Text editors use this feature for doing color syntax highlighting and other operations. Whenever the object properties are changing during run time then we are applying Regular Expression. When to use SetToProperty method and Regular Expression? 1. Whenever we are using Object Repository 2. Whenever we are using Descriptive Programming then we have to use only Regular Expression 3. Whenever there is fixed change on properties, for an object and using OR then we can use SetToProperty method 4. Whenever there is no fixed changes on properties, for an object with OR without OR then we can use RE Applying Regular Expression through Object Repository: - Open OR-->Select required object-->in test object details area select required property and click on configure the value button-->enter RE string pattern-->check regular expression check box-->click on OK button. Applying Regular Expression through Descriptive programming: - Set objDlg = Description.Create objDlg ("text").Value = "Fax Order No. *.*" objDlg("text").RegularExpression = True MsgBox Window("Flight Reservation").Dialog(objDlg).Exist Regular Expression Characters: - 1. Match any Single Character (.): - The “.” Character matches any single character for example,”...” will match “12b”,”b3b”,”123”,”abc”,”$g#”etc… 2. Match any Single Character in List [xyz]: - A character list inside square brackets matches any of the single characters in the list. For example”[abc][12]” will match “a1”, “a2”, “b1”, “b2”, “c1”, “c2”etc… 3. Match any Single Character not in List [^xyz]: - The “^” character is a negation character used to exclude a pattern from the Regular Expression. For example, “[^a][12]” will not match “a1”, and “a2” but will match “11”, “12”, “c1” etc…
  • 79. 4. Match any Single Character in Within a Range[x-z]: - The “[d-h]” construct will match any character ranging from d to h. for example, “[abcdef][123]” can also be written as “[a-f][1-3]” 5. Match Zero or More Specific Characters (*): - The “*” character is used to match Zero or more occurrences of regular expression that precedes the star. For example, “a*” will match a blank string, “a”, “aa”, “aaa”, “aaaa”, etc… “User.*” will match any string starting with text “User” 6. Match One or More Specific Characters (+): - The “+” character is used to match one or more occurrences of a RE that precedes the plus sign. For example “aa” can also be written as “a+”. “123+” will match “123”, “1233”, “123333”, etc… “[123]+” will match “1”, “2”, “3”, “12”, “23”, etc… 7. Match Zero or one Specific Character (?): - A “?” character is used to match Zero or one occurrences of a proceeding RE. For example, “a[123]?” will match “a”, “a1”, “a2” and “a3” QTP - Chapter XVIII -XIX ***Working with Web Tables*** Finding number of Rows in Web Table: - Ex: -MsgBox Browser("Rediff").Page("Rediff").WebTable("Scheme").RowCount Finding number of Columns in Web Table: - Ex: -MsgBox Browser("Rediff").Page("Rediff").WebTable("Scheme").ColumnCount(1) Retrieving Required Cell Data: - Ex: - MsgBox Browser("Rediff").Page("Rediff").WebTable("Scheme").GetCellData(2,5) ScriptNo42: - Write a script to copy Web Table content in to Excel Set objXl = CreateObject("Excel.Application") Set objWrkBk = objXl.Workbooks.Add Set objWrkSht = objWrkBk.Worksheets("sheet1") Set obj = Browser("rediff").Page("rediff") iRowCnt = obj.WebTable("rediff").RowCount iColCnt = obj.WebTable("rediff").ColumnCount(1) For iRowNum = 1To iRowCnt For iColNum = 1 To iColCnt sString = obj.WebTable("rediff").GetCellData(iRowNum,iColNum) objWrkSht.Cells(iRowNum,iColNum) = sString Next Next objWrkBk.SaveAs"C:Documents and SettingsASBDesktopscriptscript.xls" objWrkBk.Close objXl.Quit Set objWrkSht = Nothing
  • 80. Set objWrkBk = Nothing Set objXl = Nothing Web Tables ScriptNo45: - Write a script to find link existence in given cell, if it exist click on it in web table (Ex: - Row number 1 and column number 1) iFlag = 0 iObjCnt = Browser("WebTable").Page("WebTable").WebTable("gmail").ChildItemCount(1,1,"Link") 'MsgBox iObjCnt If iObjCnt > 0 Then For index = 0 To iObjCnt - 1 Set obj = Browser("WebTable").Page("WebTable").WebTable("gmail").ChildItem(1,1,"Link",index) sLnkName = obj.GetRoProperty("Name") If sLnkName = "gmail" Then iFlag = 1 obj.Click End If Next End If If iFlag = 0 Then MsgBox "Given Link is not found" End If ScriptNo46: - Delete the rows that have less then are equals to 6 years experience Set obj = Browser("Employee").Page("Employee") iRowCnt = obj.WebTable("Employee").RowCount For iRowNum = 2 To iRowCnt iExp = obj.WebTable(iRowNum,3) Set objCnt = obj.WebTable("Employee").ChildItemCount(iRowNum,1,"WebCheckBox") If objCnt > 0 Then
  • 81. Set objChBx = obj.WebTable("Employee").ChildItem(iRowNum,1,"WebCheckBox",0) objChBx.Set"ON" Set objCnt = obj.WebTable("Employee").ChildItemCount(iRowNum,5,"WebButton") If objCnt > 0 Then Set objBtn = obj.WebTable("Employee").ChildItem(iRowNum,5,"WebButton",0) If objBtn.GetROProperty("Enabled") Then objBtn.Click Else MsgBox "Delete Button is disabled in the row num:"&iRowNum End If Else MsgBox "Delete button is not exist in row Number"&iiRowNum End If Next ________________________________________________________________________________ Chapter XIX Working with Database Whenever test data based on database then we execute the queries and retrieve the data then we use QTP and Database connections. Creating a Database Connection: - Creating Database object: - Set objDb = CreateObject ("ADODB.Connection") Creating Table Object: - Set objTable = CreateObject ("ADODB.RecordSet") Setup QTP and Database Connection: - objDb.Open"DSN=QT_Flight32" Validate the Connection Status: - MsgBox objDb.State Executing Query: - objTable.Open"Select customer_name from orders",objDb objTable.Open"Select customer_name from orders order by order_number desc",objDb Retrieve the data after executing Query: - MsgBox objTable("customer_name") Retrieving all the data: - While objTable.EOF = "False" Print objTable("customer_name") objTable.MoveNext Wend ScriptNo47: - Write a script to retrieve the data from Database for given orders and maintain order information in excel file.
  • 82. What is adodb connection? The ADO (ActiveX Data Objects) Connection object is used to create a connection to a data source. Through this connection, you can access and manipulate a database. What is adodb RecordSet? The ADO Recordset object is used to hold a set of records from a database table. To be able to read database data, the data should be loaded into a recordset.
  • 83. Note: The database we are using here is MS Access. Before running this script creates a table in MS - Access. In the above script I used table called "emp" and column 'names as "v1" and "v2". "D: testdata.mdb" is path of the table which we created. The main use of this script is to use test data of table (which is in ' database) in the application. In the above script we are passing values from database to Textboxes in Windows Application.
  • 84. QTP – QC Integration Converting a manual test case in to Test Script: - Prerequisites: - QUICKTEST_TEST add-in should be installed Navigation: - QCTest PlanSelect Required Test CaseSelect Design Steps TabFrom Generate Script
  • 85. DropdownSelect QUICKTEST_TESTObserve that Manual Test Case icon is changed to Automation icon (QTP) Select Test Script TabObserve that QTP Test script is generated and Lunch QTP icon is available. If we click on lunch QTP icon if lunches QTP with required script, but all add-ins will disable except “WEB” Add- In. That is the reason after convert manual test case in to test script we open QC Test Script from QTP. To do this we required QTP and QC Integrations. QTP – QC Integration: - Navigation: - QTP while lunching QTP select require add-inFile menuSelect Quality Center ConnectionEnter URL forQCClick Connect ButtonEnter User Name and passwordclick Authenticate buttonSelect domain and project and click login button. After Integration doneClick Openobserve that Quality Center Test Plan icon is displayedClick on itBrowse and open required test scriptfile menuSettingClick modify buttoncheck required add-ins check boxClick OKClick Save. After opened Test Script displays below: - 1. All steps, user actions and expected results are displaying as comments. 2. Remove all comments if we want, design a test script for the same and save test script Executing a Test Script: - Navigation: - Step1: - We need to add Test Plan Test Scripts to Test Lab Navigation: - Test LabSelect required TestSetClick Select Test ButtonFrom Right side pane select required test scripts and click add to test set buttonclick Left arrow iconClick refresh button. Step2: - We can execute in two ways Way 1: - QTPopen a QC TestScriptClick Run ButtonCheck “New Run Results in Quality Center project” radio ButtonSelect Required TestSetClick OK Button. Way 2: - TestLabSelect TestSetselect required test ScriptsClick Run Buttoncheck “Run All Test locally” and enable Log Check BoxClick Run All button. View Test Results: - After executing a TestScripts QTP save the Test Results in respective TestLab TestSetGo to the corresponding TestSetDouble Click on required executed TestScriptSelect required RunClick Lunch report button Recovery Scenario manager QTP recovery scenarios provide a method for scripts to recover from different types of run time error conditions. This is requiring for an un-attended test case execution. When not to use recovery scenarios? Consider the following code, which has the potential to generate a divide by zero error exception: „Sample code with error probability Y = z-2 Y = 4/y We can handle this class or error using the ON Error Statement: „Handling predictable errors Z = 2 Y = 4/y On Error Resume Next X = 4/y If Err.Number = 11 then MsgBox “Error code divide by zero handled” Else „Un Known error. Handler for Un Known errors. MsgBox Err.Description &”. “&Err.Source
  • 86. EndIf The above scenario produces a predicated specific error in a specific location in the code. This type of situation can only be handed using the “OnErrorResumeNext” statement rather than a recovery scenario. When to use Recovery Scenario: - We can use a recovery scenario when we know what type of error can occur but don‟t know A recovery scenario consists of following components: A Trigger Event: - It is event that unexpectedly interrupts script execution. This event can be any one of the following: Pop-up window Object State Test run Error Post Recovery Action: - This specified what should be done once the recovery action has been successfully completed and this can be any one of the following: Repeat Current Steps and Continue Proceed to next step Proceed to next action iteration Proceed to next test iteration Restart current test run Stop the test run Navigation for Applying RSM: - Resource MenuRecovery Scenario ManagerClick on new scenarioclick on next button in wizardselect trigger Event and identify corresponding objectclick nextselect recovery operationclick on next buttonnextEnter name and descriptionClick on next buttonClick on FinishSave the created with “.qrs” extension Associated Created RSM: - FileSettingsRecovery tabClick on “+” button and browse the corresponding recovery fileclick on Add scenario buttonclick Apply buttonclick OK button. Disassociated Created RSM: - FileSettingsRecovery tabselect associated fileClick on “-” buttonclick Apply buttonclick OK button. Error Handling: - By using OnErrorResumeNext statement we can handle runtime error. It closes runtime error and continue to next step. Err.Number: It holds the runtime error number Err.Clear: It clears the runtime error number QTP - Chapter XXII - XXIII Object Identification It is a mechanism of how QTP is recognizing the objects uniquely Object Identification: - 1. Normal Identification
  • 87. 2. Smart Identification Normal Identification: - It is divided into 2 properties a) Mandatory Properties b) Assistance Properties Mandatory Properties: - The properties which are mandatory to recognize, are called mandatory Properties Ex: -Name, Text, Class Name, attached text…etc. Assistive properties: - these are assistance for mandatory properties. Window based Applications: Window id Web Based Applications: html id, html tag Whenever we are adding an object to OR, QTP takes all mandatory properties and analyze whether these are sufficient to recognize the object. If mandatory properties are not sufficient then it takes assistive properties one by one, and analyze for identification. If provided assistive property is also not sufficient then QTP takes the help of “Ordinal Identifiers”. We have 3 Ordinal identifiers Index, Location, Creation Time (For Browser) Index with respective theapplication and location is with respective Desktop. Smart Identification: - It is divided in to 2 Properties 1. Base Filter Properties 2. Optional Filter Properties àGenerally we are not using smart identification ________________________________________________________________________ Chapter XXIII Framework
  • 88. Question: - What is Framework? Framework is an environment, where we can maintain automation testing process. We maintain the environment in the form of folder structure. Question: - Why do we require framework? 1. To make user friendly 2. To avoid Re-Work 3. For better maintenance/ process maintenance Question: - How do you decide your Framework It is with respect to client requirement If we maintain manual testing process in quality center then we maintain in QC else we maintain in network/ shared drivers Question: - Characteristics of Framework 1. Framework should be user friendly 2. Framework should avoid Re-Work 3. Framework should be good maintenance/ maintainability Framework Folder Structure: -
  • 89. Auto Frame: - It is a parent folder and it is a framework name. It contains bellow sub folders. Documents, Data Library, Test Script, Function Library, Environment Variables, Logs, OR, Recovery Documents: - It is used to maintain project related documents like Requirements, test cases, Automation Feasibility, Test Plan…etc. Data Library: - This folders is used to maintaining files like .xls and Notepad Ex: - Run manager.xls Test Case related data.xls Queries in Notepad Runmanager.xls: - It contains all test scripts with execution status YES/ NO. Test Scripts: - In this folder we maintain automation test scripts Functional Library: - It is used to maintain common functions and business functions Common Function: - Function which are related to Framework Business Framework: - Function which are related to Test Cases (AUT). Environment Variable: - To maintain External Environment files (.xml) Logs: - It is used to analyze and store test results During execution of test scripts, framework is creating a runtime[with system date time as name] folder and creates Excel Reports, HTML Reports, Performance Reports, Screen Shots folders in Runtime folders. o Excel reports: - This folder is used to save and analyze results in Excel o HTML reports: - This folder is used to save and analyze results in HTML o Performance reports: - This folder is used to save and analyze test script performance o Screen shots: - This is used to save and analyze screen for failed test scripts OR: - It is used to maintain shared object file Recovery: - It is used to maintains recovery files InitScript.vbs: - It is initialize vbs files, if we execute it. It does below o It lunches QTP with require ADD-Ins o Open driver script and executes o Close QTP after executing test scripts Driver Scripts File: - To open and execute the required scripts selecting from excel Types of Framework: -
  • 90. 1. Linear Framework 2. Data Driven Framework 3. Keyword Driven Framework 4. Modular Driven framework 5. Hybrid Framework Linear Framework: - In this framework we design and maintain the scripts independently. We are not designing test scripts without reusability. Data Driven Framework: - Maintaining the test scripts to execute with multiple Test Data. Keyword Driven Framework: - Implementing scripts reusability by using Functions. Modular Driven Framework: - Implementing scripts reusability by using Actions. Hybrid Framework: - Combination of one or more framework. Generally we use hybrid with Data Driven and Key Word Driven Frameworks Selenium Introduction Test Automation for Web Applications Many, perhaps most, software applications today are written as web-based applications to be run in an Internet browser. The effectiveness of testing these applications varies widely among companies and organizations. In an era of highly interactive and responsive software processes where many organizations are using some form of Agile methodology, test automation is frequently becoming a requirement for software projects. Test automation is often the answer. Test automation means using a software tool to run repeatable tests against the application to be tested. For regression testing this provides that responsiveness. There are many advantages to test automation. Most are related to the repeatability of the tests and the speed at which the tests can be executed. There are a number of commercial and open source tools available for assisting with the development of test automation. Selenium is possibly the most widely-used open source solution. This user‟s guide will assist both new and experienced Selenium users in learning effective techniques in building test automation for web applications. This user‟s guide introduces Selenium, teaches its features, and presents commonly used best practices accumulated from the Selenium community. Many examples are provided. Also, technical information on the internal structure of Selenium and recommended uses of Selenium are provided. Test automation has specific advantages for improving the long-term efficiency of a software team‟s testing processes. Test automation supports: Frequent regression testing Rapid feedback to developers Virtually unlimited iterations of test case execution Support for Agile and extreme development methodologies Disciplined documentation of test cases Customized defect reporting Finding defects missed by manual testing To Automate or Not to Automate?
  • 91. Is automation always advantageous? When should one decide to automate test cases? It is not always advantageous to automate test cases. There are times when manual testing may be more appropriate. For instance, if the application‟s user interface will change considerably in the near future, then any automation might need to be rewritten anyway. Also, sometimes there simply is not enough time to build test automation. For the short term, manual testing may be more effective. If an application has a very tight deadline, there is currently no test automation available, and it‟s imperative that the testing get done within that time frame, then manual testing is the best solution. Introducing Selenium Selenium is a set of different software tools each with a different approach to supporting test automation. Most Selenium QA Engineers focus on the one or two tools that most meet the needs of their project, however learning all the tools will give you many different options for approaching different test automation problems. The entire suite of tools results in a rich set of testing functions specifically geared to the needs of testing of web applications of all types. These operations are highly flexible, allowing many options for locating UI elements and comparing expected test results against actual application behavior. One of Selenium‟s key features is the support for executing one‟s tests on multiple browser platforms. Brief History of The Selenium Project Selenium first came to life in 2004 when Jason Huggins was testing an internal application at ThoughtWorks. Being a smart guy, he realized there were better uses of his time than manually stepping through the same tests with every change he made. He developed a Javascript library that could drive interactions with the page, allowing him to automatically rerun tests against multiple browsers. That library eventually became Selenium Core, which underlies all the functionality of Selenium Remote Control (RC) and Selenium IDE. Selenium RC was ground-breaking because no other product allowed you to control a browser from a language of your choice. While Selenium was a tremendous tool, it wasn‟t without its drawbacks. Because of its Javascript based automation engine and the security limitations browsers apply to Javascript, different things became impossible to do. To make things worse, webapps became more and more powerful over time, using all sorts of special features new browsers provide and making this restrictions more and more painful. In 2006 a plucky engineer at Google named Simon Stewart started work on a project he called WebDriver. Google had long been a heavy user of Selenium, but testers had to work around the limitations of the product. Simon wanted a testing tool that spoke directly to the browser using the „native‟ method for the browser and operating system, thus avoiding the restrictions of a sandboxed Javascript environment. The WebDriver project began with the aim to solve the Selenium‟ pain-points. Jump to 2008. The Beijing Olympics mark China‟s arrival as a global power, massive mortgage default in the United States triggers the worst international recession since the Great Depression, The Dark Knight is viewed by every human (twice), still reeling from the untimely loss of Heath Ledger. But the most important story of that year was the merging of Selenium and WebDriver. Selenium had massive community and commercial support, but WebDriver was clearly the tool of the future. The joining of the two tools provided a common set of features for all users and brought some of the brightest minds in test automation under one roof. Perhaps the best explanation for why WebDriver and Selenium are merging was detailed by Simon Stewart, the creator of WebDriver, in a joint email to the WebDriver and Selenium community on August 6, 2009. “Why are the projects merging? Partly because webdriver addresses some shortcomings in selenium (by being able to bypass the JS sandbox, for example. And we‟ve got a gorgeous API), partly because selenium addresses some shortcomings in webdriver (such as supporting a broader range of browsers) and partly because the main selenium contributors and I felt that it was the best way to offer users the best possible framework.” Selenium’s Tool Suite
  • 92. Selenium is composed of multiple software tools. Each has a specific role. Selenium 2 (aka. Selenium Webdriver) Selenium 2 is the future direction of the project and the newest addition to the Selenium toolkit. This brand new automation tool provides all sorts of awesome features, including a more cohesive and object oriented API as well as an answer to the limitations of the old implementation. As you can read in Brief History of The Selenium Project, both the Selenium and WebDriver developers agreed that both tools have advantages and that merging the two projects would make a much more robust automation tool. Selenium 2.0 is the product of that effort. It supports the WebDriver API and underlying technology, along with the Selenium 1 technology underneath the WebDriver API for maximum flexibility in porting your tests. In addition, Selenium 2 still runs Selenium 1‟s Selenium RC interface for backwards compatibility. Selenium 1 (aka. Selenium RC or Remote Control) As you can read in Brief History of The Selenium Project, Selenium RC was the main Selenium project for a long time, before the WebDriver/Selenium merge brought up Selenium 2, the newest and more powerful tool. Selenium 1 is still actively supported (mostly in maintenance mode) and provides some features that may not be available in Selenium 2 for a while, including support for several languages (Java, Javascript, Ruby, PHP, Python, Perl and C#) and support for almost every browser out there. Selenium IDE Selenium IDE (Integrated Development Environment) is a prototyping tool for building test scripts. It is a Firefox plugin and provides an easy-to-use interface for developing automated tests. Selenium IDE has a recording feature, which records user actions as they are performed and then exports them as a reusable script in one of many programming languages that can be later executed. Note Even though Selenium IDE has a “Save” feature that allows users to keep the tests in a table-based format for later import and execution, it is not designed to run your test passes nor is it designed to build all the automated tests you will need. Specifically, Selenium IDE doesn‟t provide iteration or conditional statements for test scripts. At the time of writing there is no plan to add such thing. The reasons are partly technical and partly based on the Selenium developers encouraging best practices in test automation which always requires some amount of programming. Selenium IDE is simply intended as a rapid prototyping tool. The Selenium developers recommend for serious, robust test automation either Selenium 2 or Selenium 1 to be used with one of the many supported programming languages. Selenium-Grid Selenium-Grid allows the Selenium RC solution to scale for large test suites and for test suites that must be run in multiple environments. Selenium Grid allows you to run your tests in parallel, that is, different tests can be run at the same time on different remote machines. This has two advantages. First, if you have a large test suite, or a slow- running test suite, you can boost its performance substantially by using Selenium Grid to divide your test suite to run different tests at the same time using those different machines. Also, if you must run your test suite on multiple environments you can have different remote machines supporting and running your tests in them at the same time. In each case Selenium Grid greatly improves the time it takes to run your suite by making use of parallel processing. Choosing Your Selenium Tool Many people get started with Selenium IDE. If you are not already experienced with a programming or scripting language you can use Selenium IDE to get familiar with Selenium commands. Using the IDE you can create simple tests quickly, sometimes within seconds.
  • 93. We don‟t, however, recommend you do all your test automation using Selenium IDE. To effectively use Selenium you will need to build and run your tests using either Selenium 2 or Selenium 1 in conjunction with one of the supported programming languages. Which one you choose depends on you. At the time of writing the Selenium developers are planning on the Selenium-WebDriver API being the future direction for Selenium. Selenium 1 is provided for backwards compatibility. Still, both have strengths and weaknesses which are discussed in the corresponding chapters of this document. We recommend those who are completely new to Selenium to read through these sections. However, for those who are adopting Selenium for the first time, and therefore building a new test suite from scratch, you will probably want to go with Selenium 2 since this is the portion of Selenium that will continue to be supported in the future. Supported Browsers and Platforms In Selenium 2.0, the supported browsers vary depending on whether you are using Selenium-WebDriver or Selenium- RC. Selenium-WebDriver Selenium-WebDriver supports the following browsers along with the operating systems these browsers are compatible with. Google Chrome 12.0.712.0+ Internet Explorer 6, 7, 8, 9 - 32 and 64-bit where applicable Firefox 3.0, 3.5, 3.6, 4.0, 5.0, 6, 7 Opera 11.5+ HtmlUnit 2.9 Android – 2.3+ for phones and tablets (devices & emulators) iOS 3+ for phones (devices & emulators) and 3.2+ for tablets (devices & emulators) Note: At the time of writing there is an emulator bug with Android 2.3 that prevents the driver from working properly on device emulators. However, it works fine on tablet emulators and real devices. Selenium 1.0 and Selenium-RC. This is the old, support platform for Selenium 1.0. It should still apply to the Selenium 2.0 release of Selenium-RC. Browser Selenium IDE Selenium 1 (RC) Operating Systems Firefox 3.x Record and playback tests Start browser, run tests Windows, Linux, Mac Firefox 3 Record and playback tests Start browser, run tests Windows, Linux, Mac Firefox 2 Record and playback tests Start browser, run tests Windows, Linux, Mac IE 8 Test execution only via Selenium RC*Start browser, run tests Windows IE 7 Test execution only via Selenium RC*Start browser, run tests Windows IE 6 Test execution only via Selenium RC*Start browser, run tests Windows Safari 4 Test execution only via Selenium RC Start browser, run tests Windows, Mac Safari 3 Test execution only via Selenium RC Start browser, run tests Windows, Mac Safari 2 Test execution only via Selenium RC Start browser, run tests Windows, Mac Opera 10 Test execution only via Selenium RC Start browser, run tests Windows, Linux, Mac Opera 9 Test execution only via Selenium RC Start browser, run tests Windows, Linux, Mac Opera 8 Test execution only via Selenium RC Start browser, run tests Windows, Linux, Mac Google ChromeTest execution only via Selenium RC Start browser, run tests Windows, Linux, Mac
  • 94. Others Test execution only via Selenium RC Partial support possible**As applicable * Tests developed on Firefox via Selenium IDE can be executed on any other supported browser via a simple Selenium RC command line. ** Selenium RC server can start any executable, but depending on browser security settings there may be technical limitations that would limit certain features. Flexibility and Extensibility You‟ll find that Selenium is highly flexible. There are many ways you can add functionality to both Selenium test scripts and Selenium‟s framework to customize your test automation. This is perhaps Selenium‟s greatest strength when compared with other automation tools. These customizations are described in various places throughout this document. In addition, since Selenium is Open Source, the sourcecode can always be downloaded and modified. What’s in this Book? This user‟s guide targets both new users and those who have already used Selenium but are seeking additional knowledge. We introduce Selenium to new users and we do not assume prior Selenium experience. We do assume, however, that the user has at least a basic understanding of test automation. For the more experienced user, this guide can act as a reference. For the more experienced, we recommend browsing the chapter and subheadings. We‟ve provided information on the Selenium architecture, examples of common usage, and a chapter on test design techniques. The remaining chapters of the reference present: Selenium IDE Introduces Selenium IDE and describes how to use it to build test scripts. using the Selenium Integrated Development Environment. If you are not experienced in programming, but still hoping to learn test automation this is where you should start and you‟ll find you can create quite a few automated tests with Selenium IDE. Also, if you are experienced in programming, this chapter may still interest you in that you can use Selenium IDE to do rapid prototyping of your tests. This section also demonstrates how your test script can be “exported” to a programming language for adding more advanced capabilities not supported by Selenium IDE. Selenium 2 Explains how to develop an automated test program using Selenium 2. Selenium 1 Explains how to develop an automated test program using the Selenium RC API. Many examples are presented in both programming languages and scripting languages. Also, the installation and setup of Selenium RC is covered here. The various modes, or configurations, that Selenium RC supports are described, along with their trade-offs and limitations. An architecture diagram is provided to help illustrate these points. Solutions to common problems frequently difficult for new Sel-R users are described here, for instance, handling Security Certificates, https requests, pop-ups, and the opening of new windows. Test Design Considerations This chapter presents programming techniques for use with Selenium-WebDriver and Selenium RC. We also demonstrate techniques commonly asked about in the user forum such as how to design setup and teardown functions, how to implement data-driven tests (tests where one can vary the data between test passes) and other methods of programming common test automation tasks. Selenium-Grid This chapter is not yet developed.
  • 95. User extensions Describes ways that Selenium can be modified, extended and customized. The Documentation Team–Authors Past and Present In alphabetical order, the following people have made significant contributions to the authoring of this user‟s guide, its publishing infrastructure, or both. We are very grateful to all of them. Dave Hunt Luke Inman-Semerau Mary Ann May-Pumphrey Noah Sussman Paul Grandjean Peter Newhook Santiago Suarez-Ordonez Simon Stewart Tarun Kumar Acknowledgements A special thanks goes to Patrick Lightbody. As an administrator of the SeleniumHQ website, major contributor to Selenium RC, his support was invaluable when writing the first release of the user‟s guide. Patrick helped us understand our audience. He also set us up with everything we needed on the seleniumhq.org website for publishing the documents. Also a thanks goes to Andras Hatvani for his advice on publishing solutions, and to Amit Kumar for participating in our discussions and for assisting with reviewing the document. And of course, we must recognize the Selenium Developers. They have truly designed an amazing tool. Without the vision of the original designers, and the continued efforts of the current developers, we would not have such a great tool to pass on to you.