VB Scripting Ultimate
VB Scripting Ultimate
VB Scripting Ultimate
VB Script Variables Definition 1): Variable is a named memory location for storing program information Definition 2): A variable is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running. Purpose of Variable: a) Comparing values Example: Dim x,y,a x=100 y=100 a=x=y Msgbox a 'It returns True b) Holding Program Result Example: Cost=Tickets*Price c) Passing parameters d) To store data that returned by functions Example: myDate=Now It returns current data & time e) To hold data Example: myName=gcreddy Declaring Variables We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. For Example: Dim x, y, city, gcreddy We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in our script. Option Explicit Statement Forces explicit declaration of all variables in a script. Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. A variable name: a) Must begin with an alphabetic character. Dim abc Dim 9ab Dim ab9 'Right 'Wrong 'Right
Dim ab c 'wrong Dim ab_c 'Right c) Must not exceed 255 characters. d) Must be unique in the scope in which it is declared. Scope of Variables A variable's scope is determined by where we declare it. When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable. If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope. Example: Dim x,y,z x=10 y=20 z=x+y msgbox z 'Returns 30
Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90 End Function Call res
Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: A = 200 City = Hyderabad X=100: Y=200 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so this array actually contains 4 elements. We assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 4, data can be assigned to the elements of an array as follows: A(0) = 256 A(1) = 324 A(2) = 100 A(3) = 55 Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5, 10) In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns. Dynamic Arrays We can also declare an array whose size changes during the time our script is running. This is called a dynamic array.
The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example: Dim MyArray() ReDim AnotherArray() To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place. ReDim MyArray(25) ReDim Preserve MyArray(30) There is no limit to the number of times we can resize a dynamic array, although if we make an array smaller, we lose the data in the elimina
VB Script Operators VB Script Operators Operators are used for performing mathematical, comparison and logical operations. VB Script has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators. Operator Precedence When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained. When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence. 1) Arithmetic Operators: Operator Description 1) Exponentiation Operator (^) Raises a number to the power of an exponent 2) Multiplication Operator (*) Multiplies two numbers. 3) Division Operator (/) Divides two numbers and returns a floating-point result. 4) Integer Division Operator (\) Divides two numbers and returns an integer result. 5) Mod Operator Divides two numbers and returns only the remainder.
6) Addition Operator (+) Sums two numbers. 7) Subtraction Operator (-) Finds the difference between two numbers or indicates the negative value of a numeric expression. 8) Concatenation Operator (&) Forces string concatenation of two expressions. Example: Dim a,b,c a=10 b=3 c=a^b msgbox c '1000 c=a*b msgbox c '30 c=a/b msgbox c '3.33333333 c=a\b msgbox c '3 c=a mod b msgbox c '1 c=a-b msgbox c '7 Dim a,b,c a=10 b=2 c=3 d=c*a^b 'c=a+b msgbox d '1000 Addition (+) operator Dim a,b,c a=10 b=2 c=a+b msgbox c '12 (if both are numeric, then it adds) a="10" b=2 c=a+b msgbox c '12 (one is string another numeric, then it adds) a="10" b="2" c=a+b msgbox c '102 (if both are strings, then it concatenates) a="hydera" b="bad" c=a+b msgbox c 'hyderabad a="gagan" b=2
c=a+b msgbox c 'error Concatenation Operator Dim a,b,c a=10 b=2 c=a&b msgbox c '102 a="10" b=2 c=a&b msgbox c '102 a="10" b="2" c=a&b msgbox c '102 a="hydera" b="bad" c=a&b msgbox c '102 2) Comparison Operators Used to compare expressions. Operator Description 1) = (Equal to) Used to compare expressions. 2) <> (Not equal to) Used to compare expressions. 3) < Less than 4) > Grater than 5) <= Less than or equal to 6) >= Greater than or equal to 7) Is Object equivalence Example: Dim x,y,z x=10 y=20 z=x=y Msgbox z 'False x=10 y=20 z=x>y Msgbox z 'False x=10 y=20 z=x>=y Msgbox z 'False x=10 y=20 z=x<>y Msgbox z 'True x=10 y=20
z=x<y Msgbox z 'True x=10 y=20 z=x<=y Msgbox z 'True 3) Concatenation Operators Operator Description 1) Addition Operator (+) Sums two numbers If Then 1) Both expressions are numeric Add. 2) Both expressions are strings Concatenate. 3) One expression is numeric and the other is a string Add. 2) Concatenation Operator (&) Forces string concatenation of two expressions.
4) Logical Operators Operator Description Syntax 1) Not Performs logical negation on an expression result= Not expression 2) And Performs a logical conjunction on two expressions. result= expression1 And expression2 3) Or Performs a logical disjunction on two expressions. result= expression1 Or expression2 4) Xor Performs a logical exclusion on two expressions. result= expression1 Xor expression2 5) Eqv Performs a logical equivalence on two expressions. result= expression1 Eqv expression2 6) Imp Performs a logical implication on two expressions. result= expression1 Imp expression2
Looping Through Code Flow Control (Loop Statements) o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False; o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times. The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array. 1) Using Do Loops We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. a) Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True i) Do While condition Statements ---------------------
Loop Or, we can use this below syntax: Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" Loop ii) Do Statements --------------------Loop While condition Example: Dim x x=1 Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 b) Repeating a Statement Until a Condition Becomes True iii) Do Until condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP" Loop Or, we can use this below syntax: iv) Do Statements --------------------Loop Until condition Or, we can use this below syntax: Example: Dim x x=1 Do Msgbox Hello G.C.Reddy Msgbox "Hello QTP" x=x+1 Loop Until x=5
2 While...Wend Statement Executes a series of statements as long as a given condition is True. Syntax: While condition Statements --------------------Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G.C.Reddy" msgbox "Hello QTP" Wend 3) For...Next Statement Repeats a group of statements a specified number of times. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.C.Reddy" Next 4) For Each...Next Statement Repeats a group of statements for each element in an array or collection. Syntax: For Each item In array Statements Next Example: (1 Dim a,b,x (3) a=20 b=30 x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next Example: (2 MyArray = Array("one","two","three","four","five") For Each element In MyArray
VB Script Procedures User Defined Functions In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure. 1) Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). Syntax: Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1, argument2) Statements --------------------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2 2) Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements --------------------End Function
Or Function Procedure name (argument1, argument2) Statements --------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function 3) Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas. 4) Using Sub and Function Procedures in Code A Function in our code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees." To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. 5) Examples: (here, I used Flight Reservation Application for creating Functions, why because, It is the default application for QTP, anybody can practice easily...G C Reddy) '******************************************* ' Login Operation '******************************************* Function Login(Agent,Pwd) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Pwd Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(10) Then Login="Login Operation Sucessful" 'Msgbox Login else Login="Login Operation Unsucessful" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click 'Msgbox Login End If End Function '*************************************** ' Closing Application '*************************************** Function Close_App() if Window("Flight Reservation").Exist(3) Then Window("Flight Reservation").Close End If End Function '*************************************** ' Open Order '*************************************** Function Open_Order(ord) ordnum=0 On Error Resume Next Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty ("text") ordnum=cdbl (ordnum) If ord=ordnum Then Open_Order= "Order Number "&ordnum&" Opened Sucuessfully" 'Msgbox Open_Order else Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available" Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click 'Msgbox Open_Order End If End Function '****************************************** ' Update Order '****************************************** Function Update_Order(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click wait(10) update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text") If update="Update Done..." Then Update_Order= "Order Updated Sucussfully" 'Msgbox Update_Order Else Window("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").Click
Update_Order= "Order Not Updated" 'Msgbox Update_Order End If End Function '****************************************** ' Function to send a mail '****************************************** Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit Set m = Nothing Set otl = Nothing End Function Call SendMail("[email protected]","hi","This is test mail for testing","")
VB Script Errors Generally Errors in VB Script are 2 Types 1) VB Script Run-time Errors VB Script run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated. Error Number Description: 429 ActiveX component can't create object 507 An exception occurred 449 Argument not optional 17 Can't perform requested operation 430 Class doesn't support Automation 506 Class not defined 11 Division by zero 48 Error in loading DLL 5020 Expected ')' in regular expression 5019 Expected ']' in regular expression 432 File name or class name not found during Automation operation 92 For loop not initialized 5008 Illegal assignment 51 Internal error 505 Invalid or unqualified reference 481 Invalid picture 5 Invalid procedure call or argument 5021 Invalid range in character set 94 Invalid use of Null 448 Named argument not found 447 Object doesn't support current locale setting 445 Object doesn't support this action
438 Object doesn't support this property or method 451 Object not a collection 504 Object not safe for creating 503 Object not safe for initializing 502 Object not safe for scripting 424 Object required 91 Object variable not set 7 Out of Memory 28 Out of stack space 14 Out of string space 6 Overflow 35 Sub or function not defined 9 Subscript out of range 5017 Syntax error in regular expression 462 The remote server machine does not exist or is unavailable 10 This array is fixed or temporarily locked 13 Type mismatch 5018 Unexpected quantifier 500 Variable is undefined 458 Variable uses an Automation type not supported in VBScript 450 Wrong number of arguments or invalid property assignment 2) VB Script Syntax Errors VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed. Error Number Description: 1052 Cannot have multiple default property/method in a Class 1044 Cannot use parentheses when calling a Sub 1053 Class initialize or terminate do not have arguments 1058 'Default' specification can only be on Property Get 1057 'Default' specification must also specify 'Public' 1005 Expected '(' 1006 Expected ')' 1011 Expected '=' 1021 Expected 'Case' 1047 Expected 'Class' 1025 Expected end of statement 1014 Expected 'End' 1023 Expected expression 1015 Expected 'Function' 1010 Expected identifier 1012 Expected 'If' 1046 Expected 'In' 1026 Expected integer constant 1049 Expected Let or Set or Get in property declaration 1045 Expected literal constant 1019 Expected 'Loop' 1020 Expected 'Next' 1050 Expected 'Property' 1022 Expected 'Select' 1024 Expected statement 1016 Expected 'Sub' 1017 Expected 'Then' 1013 Expected 'To' 1018 Expected 'Wend' 1027 Expected 'While' or 'Until' 1028 Expected 'While,' 'Until,' or end of statement 1029 Expected 'With'
1030 Identifier too long 1014 Invalid character 1039 Invalid 'exit' statement 1040 Invalid 'for' loop control variable 1013 Invalid number 1037 Invalid use of 'Me' keyword 1038 'loop' without 'do' 1048 Must be defined inside a Class 1042 Must be first statement on the line 1041 Name redefined 1051 Number of arguments must be consistent across properties specification 1001 Out of Memory 1054 Property Set or Let must have at least one argument 1002 Syntax error 1055 Unexpected 'Next' 1015 Unterminated string constant
VB Script Functions Built-In Functions of VB Script o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3) o Math (9) o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8) Important Functions 1) Abs Function Returns the absolute value of a number. Dim num num=abs(-50.33) msgbox num 2) Array Function Returns a variant containing an Array Dim A A=Array("hyderabad","chennai","mumbai") msgbox A(0) ReDim A(5) A(4)="nellore" msgbox A(4)
3) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Dim num num=Asc("A") msgbox num * It returns the value 65 * 4) Chr Function Returns the character associated with the specified ANSI character code. Dim char Char=Chr(65) msgbox char * It returns A * 5) CInt Function Returns an expression that has been converted to a Variant of subtype Integer. Dim num num=123.45 myInt=CInt(num) msgbox MyInt 6) Date Function Returns the Current System Date. Dim mydate mydate=Date msgbox mydate 7) Day Function Ex1) Dim myday myday=Day("17,December,2009") msgbox myday Ex2) Dim myday mydate=date myday=Day(Mydate) msgbox myday 8) DateDiff Function Returns the number of intervals between two dates. Dim Date1, Date2, x Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("yyyy", Date1, Date2) Msgbox x 'Differnce in Years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("q", Date1, Date2) Msgbox x 'Differnce in Quarters Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("m", Date1, Date2) Msgbox x 'Differnce in Months Date1=#10-10-09#
Date2=#10-10-11# x=DateDiff("w", Date1, Date2) Msgbox x 'Differnce in weeks Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("d", Date1, Date2) Msgbox x 'Differnce in days Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("h", Date1, Date2) Msgbox x 'Differnce in Hours Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("n", Date1, Date2) Msgbox x 'Differnce in Minutes Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("s", Date1, Date2) Msgbox x 'Differnce in Seconds Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("y", Date1, Date2) Msgbox x 'Differnce in day of years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("a", Date1, Date2) Msgbox x 'Error Date1=#10-10-09# Date2=#10-10-11# x=DateDiff(Date1, Date2) Msgbox x 'Error 9) Hour Function Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Dim mytime, Myhour mytime=Now myhour=hour (mytime) msgbox myhour 10) Join Function Returns a string created by joining a number of substrings contained in an array. Dim mystring, myarray(3) myarray(0)="Chandra " myarray(1)="Mohan " myarray(2)="Reddy" mystring=Join(MyArray) msgbox mystring 11) Eval Function Evaluates an expression and returns the result. 12) Time Function
Returns a Variant of subtype Date indicating the current system time. Dim mytime mytime=Time msgbox mytime 13) VarType Function Returns a value indicating the subtype of a variable. Dim x,y x=100 y=VarType(x) Msgbox y '2 (Integer) x="Hyderabad" y=VarType(x) Msgbox y '8 (String) x=#10-10-10# y=VarType(x) Msgbox y '7(Date format) x=100.56 y=VarType(x) Msgbox y ' 5(Double) y=VarType(a) Msgbox y '0 (Empty) Set x =CreateObject("Scripting.FileSystemObject") y=VarType(x) Msgbox y '9(Automation Object) 14) Left Function Dim Val, x,y Val="Hyderabad" x=Left(Val,3) Msgbox x 'Hyd Val=100 x=Left(Val,1) Msgbox x '1 Val="Hyderabad" x=Left(Val,0) Msgbox x 'Null Val="Hyderabad" x=Left(Val,12) Msgbox x 'Hyderabad Val=#10-10-10# x=Left(Val,3) Msgbox x '10/ Val="Hyderabad" x=Left(Val) Msgbox x 'Error (Lengnth is Manditory)
14) Right Function Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". 15) Len Function Returns the number of characters in a string or the number of bytes required to store a variable. Ex 1): Dim Mystring mystring=Len("G.C.Reddy") msgbox mystring Ex 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring 16) Mid Function Returns a specified number of characters from a string. Dim Val, x,y Val="Hyderabad" x=Mid(Val,3,4) Msgbox x 'dera Val=100 x=Mid(Val,1) Msgbox x '100 Val="Hyderabad" x=Mid(Val,6,7) Msgbox x 'abad Val="Hyderabad" x=Mid(Val,6,1) Msgbox x 'a Val="Hyderabad" x=Mid(Val,6,0) Msgbox x 'Null Val="Hyderabad" x=Mid(Val,12) Msgbox x 'Null Val=#10-10-10# x=Mid(Val,3,3) Msgbox x '/10 Val=#2010-10-10# x=Mid(Val,5) Msgbox x '/2010 Val="Hyderabad" x=Mid(Val) Msgbox x 'Error
17) Timer Function Returns the number of seconds that have elapsed since 12:00 AM (midnight). Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTime End Function Call myTime(2000) 17) isNumeric Function Dim MyVar, MyCheck MyVar = 53 MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "459.95" MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "45 Help" MyCheck = IsNumeric(MyVar) msgbox MyCheck * It Returns True/False like Result * 18) Inputbox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 19) Msgbox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") 20) CreateObject creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system Set objFso=createobject ("Scripting.FileSystemObject") 'creates and returns reference of the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (Ms-Excel files) Set objExcel = CreateObject("Excel.Application") 'creates and returns reference of the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents Set objWord = CreateObject("Word.Application")
'creates and returns reference of the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases Set objConnection = CreateObject("ADODB.Connection") 'creates and returns reference of the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records) Set objRecordSet = CreateObject("ADODB.Recordset") 'creates and returns reference of the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations Set objPPT = CreateObject("PowerPoint.Application") Set xmldoc = WScript.CreateObject("msxml2.domdocument") 21) Round Returns a number rounded to a specified number of decimal places. Dim num num=172.499 num=Round(num) msgbox num 22) StrReverse It returns reverse value of the given sring x=strreverse ("dabaraedyh") msgbox x 23) strComp It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd) Dim x, y x="cd": y="bcd" comp=strcomp(x,y) msgbox comp 24) Replace It replace a sub string with given value (another sub string) mystring=Replace("kb script", "k","v") msgbox mystring
VB Script Functions Conversion Functions 1) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Syntax: Asc(string) Remarks The string argument is any valid string expression. If the string contains no characters, a run-time error occurs. Dim MyNumber MyNumber = Asc("A") ' Returns 65. MyNumber = Asc("a") ' Returns 97. MyNumber = Asc("Apple") ' Returns 65.
2) CByte Function Returns an expression that has been converted to a Variant of subtype Byte. Syntax: CByte(expression) The expression argument is any valid expression. Use the CByte function to provide conversions from any data type to a Byte subtype. Example: Dim MyDouble, MyByte MyDouble = 125.5678 ' MyDouble is a Double. MyByte = CByte(MyDouble) ' MyByte contains 126. 3) CDate Function Returns an expression that has been converted to a Variant of subtype Date. Syntax: CDate(date) The date argument is any valid date expression. Use the IsDate function to determine if date can be converted to a date or time. Example: MyDate = "October 19, 1962" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type. 4) Chr Function Returns the character associated with the specified ANSI character code. Syntax: Chr(charcode) The charcode argument is a number that identifies a character. Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character. Example: Dim MyChar ' Returns A: MyChar = Chr(65) ' Returns B: MyChar = Chr(66) ' Returns Z: MyChar = Chr(90) ' Returns a: MyChar = Chr(97) ' Returns b: MyChar = Chr(98) ' Returns z: MyChar = Chr(122) ' Returns 0: MyChar = Chr(48) ' Returns 1: MyChar = Chr(49) ' Returns 9: MyChar = Chr(57) ' Returns horizontal tab: MyChar = Chr(9)
' Returns >: MyChar = Chr(62) ' Returns %: MyChar = Chr(37) 5) CLng Function Returns an expression that has been converted to a Variant of subtype Long. Syntax: CLng(expression) The expression argument is any valid expression. Use the CLng function to provide conversions from any data type to a Long subtype. Example: Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428. 6) CStr Function Returns an expression that has been converted to a Variant of subtype String. Syntax: CStr(expression) The expression argument is any valid expression. Example: Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324" 7) Oct Function Returns a string representing the octal value of a number. Syntax: Oct(number) The number argument is any valid expression. Example: Dim MyOct MyOct = Oct(4) ' Returns 4. MyOct = Oct(8) ' Returns 10. MyOct = Oct(459) ' Returns 713. 8) CBool Function Returns an expression that has been converted to a Variant of subtype Boolean. Synta: CBool(expression) The expression argument is any valid expression. If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a runtime error occurs. Example: Dim A, B, Check A = 5: B = 5 ' Initialize variables. Check = CBool(A = B) ' Check contains True. A=0 ' Define variable. Check = CBool(A) ' Check contains False. 9) CCur Function
Returns an expression that has been converted to a Variant of subtype Currency. Syntax: CCur(expression) The expression argument is any valid expression. Example: Dim MyDouble, MyCurr MyDouble = 543.214588 ' MyDouble is a Double. MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292). 10) CInt Function Returns an expression that has been converted to a Variant of subtype Integer. Syntax: CInt(expression) The expression argument is any valid expression. Example: Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346. 11) CSng Function Returns an expression that has been converted to a Variant of subtype Single. Syntax: CSng(expression) The expression argument is any valid expression. Example: Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216. 12) Hex Function Returns a string representing the hexadecimal value of a number. Syntax: Hex(number) number argument is any valid expression. we can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. Example: Dim MyHex MyHex = Hex(5) ' Returns 5. MyHex = Hex(10) ' Returns A. MyHex = Hex(459) ' Returns 1CB. VB Script String Functions String Functions 1) Left Function Returns a specified number of charectors of a given string from left side Syntax: variable=Left(string,Lengh) Example:
Dim val,x val="Hyderabad" x=Left(val,3) msgbox x ' Output: Hyd val="9247837478" x=Left(val,1) msgbox x ' Output: 9 val="H92yderabad" x=Left(val,3) msgbox x ' Output: H92 x=Left(9247837478,5) msgbox x ' Output: 92478 val=#10-10-10# x=Left(val,3) msgbox x ' Output: 10/ 2) Right Function Returns a specified number of charectors of a given string from Right side Example: Dim val,x val="Hyderabad" x=Right(val,3) msgbox x ' Output: bad val="9247837478" x=Right(val,1) msgbox x ' Output: 8 val="H92yderabad" x=Right(val,3) msgbox x ' Output: bad x=Right(9247837478,5) msgbox x ' Output: 37478 val=#10-10-10# x=Right(val,5) msgbox x ' Output: /2010 3) Mid function Returns a specified number of charectors of a given string Example: Dim val,x val="Hyderabad" x=Mid(Val,5,3) msgbox x ' Output: rab
val="Hyderabad" x=Mid(Val,5) msgbox x ' Output: rabad val="9247837478" x=Mid(val,6,5) msgbox x ' Output: 37478 val="H92yderabad" x=Mid(val,1) msgbox x ' Output: H92yderabad x=Mid(9247837478,5) msgbox x ' Output: 837478 val=#10-10-10# x=Mid(val,5) msgbox x ' Output: 0/2010 4) StrReverse retuns reverse value of a string Example: Dim val,x val="Hyderabad" x=StrReverse(val) msgbox x 'Output dabaredyH val="001" x=StrReverse(val) msgbox x 'Output: 100 val=1002 x=StrReverse(val) msgbox x 'Output: 2001 val=#10-10-10# x=StrReverse(val) msgbox x 'Output: 0102/01/01 x=StrReverse("Hyderabad") msgbox x 'Output: dabaredyH x=StrReverse(100) msgbox x 'Output: 001 5) StrComp Function It compares two string (Binary and textual) if a) Both are equal, returns 0(zero) b) String 1 greater than string 2, returns 1(one) b) String 2 greater than string 1, returns -1
Example: Dim str1,str2,x str1="India" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="india" str2="INDIA" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="India" str2="Indian" x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="Ndia" x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 1 str1=100 str2=100 x=StrComp(str1,str2,1) msgbox x 'Output 0 str1=100 str2=101 x=StrComp(str1,str2,1) msgbox x 'Output -1 6) Lcase function Coverts Upper case values into Lower case Dim val,x val="HYDERABAD" x=Lcase(val) msgbox x 'Output hyderabad val="Hyderabad" x=Lcase(val) msgbox x 'Output hyderabad val="HederabaD" x=Lcase(val) msgbox x 'Output hyderabad val="hyderabad" x=Lcase(val) msgbox x 'Output hyderabad x=Lcase("HYDERABAD") msgbox x 'Output hyderabad
7) Ucase function Coverts Lower case values into Upper case Example: Dim val,x val="HYDERABAD" x=Ucase(val) msgbox x 'Output HYDERABAD val="Hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD val="HederabaD" x=Ucase(val) msgbox x 'Output HYDERABAD val="hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD x=Ucase("HYDERABAD") msgbox x 'Output HYDERABAD 8) LBound, UBound Functions Example: Dim x(3), y(4,5) Msgbox Lbound(x) '0 Msgbox UBound(x)'3 'Find size of the Array Msgbox UBound(x)+1 Msgbox Lbound(y,1) '0 Msgbox Lbound(y,2) '0 Msgbox UBound(y,1) '4 Msgbox UBound(y,2) '5
User Defined Functions User Defined Functions ---------------------------------------------------------i) Launching Application Navigation: a) Launch the Browser b) Enter / Select the URL (www.jjperfumes.com) Verification: Capture the Browser Name and Verify Function Launch_App() SystemUtil.Run C:\Program Files\Internet Explorer\IEXPLORE.EXE,",C:\Documents and Settings\Administrator,open Browser(Google).Page(Google).Sync Browser(Google).Navigate http://www.jjperfumes.com/ Wait (8) Browser_Name = Browser(Google).GetROProperty(title) If Browser_Name=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online Then Launch_App=Jjperumes.com Browser Launched Sucessfully Msgbox Launch_App Else Launch_App=Jjperumes.com Browser Not Launched Msgbox Launch_App End If End Function ii) Customer Registration Pre-Setup: Launching Application Navigation: a) Select Registration Link in jjperfumes.com homepage b) Enter all Mandatory details c) Select Submit button Verify: Capture confirmation Message and Verify Function Register(Email) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume).Link(Register).Click Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebList(usertype).Select Retailer Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(firstname).Set dfgdg Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(lastname).Set dgdfgdfg Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebList(gender).Select Male Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(address1 ).Set dfgfdgf Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(phone).Set 9222222223 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(email).Set Email Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(city).Set chennai Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebList(state).Select MS MISSISSIPPI Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(zip).Set 23456 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(password).SetSecure 3c30bbc7daa0dccb83c2941bb87fa0709d34 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(conPass).SetSecure 3c30bbcdb1f7a32d27a56f70a60f7d1e4159 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebButton(Submit).Click
Wait (5) Confirm_Message = Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_3 ).WebElement(Registered successfully.).GetROProperty(innertext) If Confirm_Message=Registered successfully. Then Register=Customer Registration Sucessful Msgbox Register Else Register=Registration Failed Msgbox Register End If End Function Function Register(Email) Set myBrowser=Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume).Link(Register).Click myBrowser.WebList(usertype).Select Retailer myBrowser.WebEdit(firstname).Set dfgdg myBrowser.WebEdit(lastname).Set dgdfgdfg myBrowser.WebList(gender).Select Male myBrowser.WebEdit(address1 ).Set dfgfdgf myBrowser.WebEdit(phone).Set 9222222223 myBrowser.WebEdit(email).Set Email myBrowser.WebEdit(city).Set chennai myBrowser.WebList(state).Select MS MISSISSIPPI myBrowser.WebEdit(zip).Set 23456 myBrowser.WebEdit(password).SetSecure 3c30bbc7daa0dccb83c2941bb87fa0709d34 myBrowser.WebEdit(conPass).SetSecure 3c30bbcdb1f7a32d27a56f70a60f7d1e4159 myBrowser.WebButton(Submit).Click Wait (5) Confirm_Message = Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_3 ).WebElement(Registered successfully.).GetROProperty(innertext) If Confirm_Message=Registered successfully. Then Register=Customer Registration Sucessful Msgbox Register Else Register=Registration Failed Msgbox Register End If End Function iii) Login Operation Pre-Requisites: a) Launching Application b) Customer Registration Navigation: a) Select Login Link in jjperfumes.com homepage b) Enter Email and Password c) Select Login Button Verify: Check existence of LogOut Link Function Login(Email, Pwd) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume).Link(Login).Click Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(username).Set Email Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebEdit(password).Set Pwd Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2 ).WebButton(Login).Click If Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_3 ).Link(Logout).Exist(10) Then Login=Login Operation Sucessful Msgbox Login Else
Login=Login Failed Msgbox Login End If End Function iv) Closing Application Navigation: a) Check the Existence of jjperfumes.com Browser b) Close the Browser window (If exists) Function Launch_App() SystemUtil.Run C:\Program Files\Internet Explorer\IEXPLORE.EXE,",C:\Documents and Settings\Administrator,open Browser(Google).Page(Google).Sync Browser(Google).Navigate http://www.jjperfumes.com/ Wait (8) Browser_Name = Browser(Google).GetROProperty(title) If Browser_Name=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online Then Launch_App=Jjperumes.com Browser Launched Sucessfully Msgbox Launch_App Else Launch_App=Jjperumes.com Browser Not Launched Msgbox Launch_App End If End Function ********************************************************** v) Login Operation In Flight Reservation Application Function Login (Agent, Password) SystemUtil.Run C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe,",C:\Program Files\HP\QuickTest Professional\samples\flight\app\,open Dialog(Login).Activate Dialog(Login).WinEdit(Agent Name:).Set Agent Dialog(Login).WinEdit(Password:).Set Password wait 2 Dialog(Login).WinButton(OK).Click If Window(Flight Reservation).Exist(12) Then Window(Flight Reservation).Close Login=Login Operation Sucessful Msgbox Login Else SystemUtil.CloseDescendentProcesses If Dialog(Login).Dialog(Flight Reservations).Exist(2) Then Dialog(Login).Dialog(Flight Reservations).WinButton(OK).Click Dialog(Login).WinButton(Cancel).Click End if Login=Login Failed Msgbox Login End if End Function vi) Open Order In Flight Reservation Application Function Open_Order(Order_Number) Window(Flight Reservation).Activate Window(Flight Reservation).WinButton(Button).Click
Window(Flight Reservation).Dialog(Open Order).WinCheckBox(Order No.).Set ON Window(Flight Reservation).Dialog(Open Order).WinEdit(Edit).Set Order_Number Window(Flight Reservation).Dialog(Open Order).WinButton(OK).Click OrdNum = Window(Flight Reservation).WinEdit(Order No:).GetVisibleText() OrdNum=CInt(OrdNum) If OrdNum=Order_Number Then Open_Order= Order_Number& Opened sucessfully Msgbox Open_Order Else Open_Order= Order_Number& Not Opened Msgbox Open_Order End If End Function vii) Update Order In Flight Reservation Application Function Update_Order(Tickets) Window(Flight Reservation).Activate Window(Flight Reservation).WinButton(Button).Click Window(Flight Reservation).Dialog(Open Order).WinCheckBox(Order No.).Set ON Window(Flight Reservation).Dialog(Open Order).WinEdit(Edit).Set 2 Window(Flight Reservation).Dialog(Open Order).WinButton(OK).Click Window(Flight Reservation).WinEdit(Tickets:).Set Tickets Window(Flight Reservation).WinButton(Update Order).Click Wait (10) Message = Window(Flight Reservation).ActiveX(Threed Panel Control).GetROProperty(text) If Message=Update Done Then Update_Order=Order Updated Sucessfully Msgbox Update_Order Else Update_Order=Order Not Updated Msgbox Update_Order End If End Function viii) Write Function to Count how many Browsers opened on desktop and close them all Function Close_Browsers() Dim oBrowser, Browsers, TotBrowsers, i Set oBrowser=Description.Create oBrowser(micclass).Value=Browser Set Browsers=Desktop.ChildObjects(oBrowser) TotBrowsers=Browsers.Count Msgbox TotBrowsers For i= 0 to TotBrowsers-1 Step 1 Browsers(i).close Next End Function ix) Write Function to Count how many Buttons available in FR Window Function Count_Buttons() Dim oButton, Buttons, TotButtons, i Set oButton=Description.Create oButton(Class Name).Value=WinButton Set Buttons=Window(text:=Flight Reservation).ChildObjects(oButton) TotButtons=Buttons.Count
Msgbox TotButtons End Function Call Count_Buttons() x) Write Function to Count how many Objects available in FR Window by specified Test Object class Function Count_Objects(Object) Dim obj, Objects, TotObjects, i Set obj=Description.Create obj(Class Name).Value=Object Set Objects=Window(text:=Flight Reservation).ChildObjects(obj) TotObjects=Objects.Count Msgbox TotObjects End Function Call Count_Objects(WinRadioButton) Call Count_Objects(WinButton) Call Count_Objects(WinEdit) Call Count_Objects(WinComboBox) xi) Write function to capture all button names one by one from Login Dialog Box Function Capture_Buttons() Dim oButton, Buttons, TotButtons, i, myButton Set oButton=Description.Create oButton(Class Name).Value=WinButton Set Buttons=Dialog(text:=Login).ChildObjects(oButton) TotButtons=Buttons.Count For i= 0 to TotButtons-1 myButton=Buttons(i).GetRoProperty(text) Msgbox myButton Next End Function Call Capture_Buttons() xii) Write function to Count Howmany Links available in Google Homepage Function Count_Links() Dim oLink, Links, TotLinks, i Set oLink=Description.Create oLink(micclass).Value=Link Set Links=Browser(title:=Google).Page(title:=Google).ChildObjects(oLink) TotLinks=Links.Count Msgbox TotLinks End Function Call Count_Links()
Regular Expressions Regular Expressions in QTP What is Regular Expression? It is a way of representing data using symbols. They are often used within matching, searching or replacing algorithms. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values.
Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in Descriptive programming. We can define a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified. We can define the text string as a regular expression, when creating a text checkpoint to check that a varying text string is displayed on our application, For XML checkpoints we can set attribute or element values as regular expressions. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character. Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character. b) Matching Any Single Character: A period (.) instructs QTP to search for any single character (except for \n). Ex: welcome. Matches welcomes, welcomed, or welcome followed by a space or any other single character. c) Matching Any Single Character in a List: Square brackets instruct QTP to search for any single character within a list of characters. Ex: To search for the date 1867, 1868, or 1869, enter: 186[789] d) Matching Any Single Character Not in a List: When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in the list except for the ones specified in the string. Example: [^ab] Matches any character except a or b. e) Matching Any Single Character within a Range: To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character. Example: For matching any year in the 2010s, enter: 201[0-9] f) Matching Zero or More Specific Characters:
An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character. For example: ca*r Matches car, caaaaaar, and cr g) Matching One or More Specific Characters: A plus sign (+) instructs QTP to match one or more occurrences of the preceding character. For example: ca+r Matches car and caaaaaar, but not cr. h) Matching Zero or One Specific Character: A question mark (?) instructs QTP to match zero or one occurrences of the preceding character. For example: ca?r Matches car and cr, but nothing else. i) Grouping Regular Expressions: Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * , + , ? , { } ). j) Matching One of Several Regular Expressions: A vertical line (|) instructs QTP to match one of a choice of expressions. k) Matching the Beginning of a Line: A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character. l) Matching the End of a Line: A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character. m) Matching Any AlphaNumeric Character Including the Underscore: \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 0-9, _). n) Matching Any Non-AlphaNumeric Character: \W instructs QTP to match any character other than alphanumeric characters and underscores. o) Combining Regular Expression Operators: We can combine regular expression operators in a single expression to achieve the exact search criteria we need. For example, start.* Matches start, started, starting, starter, and so forth. we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric characters. For example: [a-zA-Z]* To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4 digits between 10001200. The regular expression below matches any number between 0 and 1200. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)
RegExp object VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method b) Replace Method c) Test Method Regular Expressions Examples: 1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") strCurrentDirectory = objShell.CurrentDirectory Set objFolder = objFS.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Files Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) For Each objFile In colFiles bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.txt" Set objFS = CreateObject("Scripting.FileSystemObject") Set objTS = objFS.OpenTextFile(strFileName) strFileContents = objTS.ReadAll WScript.Echo "Searching Within: " WScript.Echo strFileContents objTS.Close Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) Set colMatches = objRE.Execute(strFileContents) WScript.Echo vbNewLine & "Resulting Matches:"
For Each objMatch In colMatches WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value Next
Scripting allows us to process drives, folders, and files using the FileSystemObject (FSO) object model.
Creating FileSystemObject:
b) Dictionary
c) Excel Application
d) Word Application
e) Shell
f) Network
g) PowerPoint
Creating PowerPointObject:
h) ADODB Connection
The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.
i) ADODB RecordSet
The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields).
j) ADODB Command
The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records.
k) Error
l) RegExp
n) Outlook Express
a) Dictionary Object
Dictionary Object that stores data key, item pairs. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.
Add Method Adds a key and item pair to a Dictionary object Exists Method Returns true if a specified key exists in the Dictionary object, false if it does not. Items Method Returns an array containing all the items in a Dictionary object. Keys Method Returns an array containing all existing keys in a Dictionary object. Remove Method Removes a key, item pair from a Dictionary object. RemoveAll Method The RemoveAll method removes all key, item pairs from a Dictionary object. Example:
Dictionary Objects Properties: Count Property Returns the number of items in a collection or Dictionary object. Read-only. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object. Key Property Sets a key in a Dictionary object. Item Property Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write. Examples:
Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"
objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" colKeys = objDictionary.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next objDictionary.RemoveAll colKeys = objDictionary.Keys Wscript.Echo VbCrLf & "Second run: "
objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys
Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next
Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next
objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" Wscript.Echo objDictionary.Count
objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing"
If objDictionary.Exists("Printer 4") Then Wscript.Echo "Printer 4 is in the Dictionary." Else Wscript.Echo "Printer 4 is not in the Dictionary." End If
VB Script Properties VB Script Classes Creating Classes Classes aren't a new concept in scripting. JavaScript, JScript, and other scripting languages have supported classes or similar elements for years. However, VBScript 5.0 is the first version of VBScript to support classes. To use classes in your VBScript code, you first need to obtain VBScript 5.0 by downloading the appropriate self-executable file from the Microsoft Developer Network (MSDN) Web site (http://msdn.microsoft.com/scripting) or by installing Microsoft Internet Explorer (IE) 5.0. Then you need to understand what a VBScript class is and learn how to declare, define, initialize, and instantiate a class. VBScript Classes VBScript 5.0 supports two types of objects: COM objects and Class objects (typically referred to as simply classes). VBScript COM objects have basic subtypes, such as an Integer or String. VBScript classes have an abstract subtype that encapsulates data and the functions to work with that data. You can think of a VBScript class as having a souped-up subtype that provides you with more computing power and flexibility. (Other differences exist between these two types of objects. For more information, see the Web-exclusive sidebar "How VBScript Classes and COM Objects Differ" on the Win32 Scripting Journal Web site at http://www.winntmag.com/ newsletter/scripting.
You can use classes to describe complex data structures. For example, if your application tracks customers and orders, you can define two classes for them, each with a unique set of internal data (typically called properties) and functions (typically called methods). You can then manage customers and orders as if they were native VBScript subtypes. More important, because you assign a class its properties and methods (i.e., its programming interface), you have an object-oriented tool to improve VBScript applications. Declaring a Class You use the Class statement to declare a class. This statement's syntax is: Class name ' Properties and methods go here. End Class where name is the name you give that class. You declare the properties and methods for your class between the Class and End Class clauses. For example, suppose you want to create the VBScript class FileList, which Listing 1 contains. This class manages those files in a folder that meet a filename specification that you provide. You create this class by first specifying the keyword Class followed by the class' name Class FileList. Next, you declare the class' properties and methods. FileList has two properties (FileSpec and FolderPath) and one method (Search). Declaring the FileSpec Property The FileSpec property holds the filename specification. For example, the filename specification might be C:\*.*. You want users to be able to freely read and write values to this property, so you declare FileSpec as an external, or public, variable with the Public statement Public FileSpec You can use a public variable in any script, not just the script in which you created the variable. However, if you use a public variable, you have no control over the value that users assign to the variable and no control over the value that the variable returns. Thus, you can't use public variables to hold values that you need to validate. Declaring the FolderPath Property The FolderPath property holds the full path to the folder containing the files. After a user sets a folder path, you need to validate that the folder exists, which means you can't use a public variable. Instead, you need to store the folder path in an internal, or private, variable and use two public property procedures to read and write to that variable. (Public property procedures are wrappers that hide the code that gets and sets the values of private variables.) Prefixing a private variable with the m_ string is a common scripting convention. For example, the private variable for the FolderPath property is m_folderPath. To declare m_folderPath, you use the Private statement Private m_folderPath Procedures and variables that have the Private qualifier aren't visible outside the class. In addition, private variables apply only to the script in which you created them. After you declare m_folderPath, you need to declare the two public property procedures that you'll use to read and write to that variable. The first procedure to declare is the Property Get procedure, which returns the values of properties. The second procedure is the Property Let procedure, which assigns values to properties. To declare the Property Get procedure, you use the Property Get statement Public Property Get FolderPath FolderPath = m_folderPath End Property where FolderPath is the name of that procedure. By including the Public statement with the Property Get statement, you're making the value that the FolderPath procedure returns available for public reading. Thus, by assigning FolderPath to m_folderPath, you make the value of m_folderPath available for public reading.
Generate interest for 1 to 5 years (for 1 year -7%, 2 years -8%, 3 years-9%, 4 years-10%, 5 years -11%) Dim amount, duration, intr amount=inputbox("enter amount") If amount<10000 Then msgbox "low amount" else For duration=1 to 5 If duration=1 Then intr=amount*7/100 msgbox "1 year intrest is: " &intr else if duration=2 Then intr=amount*8/100 msgbox "2 years intrest is: " &intr else if duration=3 Then intr=amount*9/100 msgbox "3 years intrest is: "&intr else if duration=4 Then intr=amount*10/100 msgbox "4 years intrest is: "&intr else if duration=5 Then intr=amount*11/100 msgbox "5 years intrest is: "&intr else msgbox "invalid data" End If End If End If End If End If Next End If VB Script Examples-II VB Script General Examples 1) Read a value and find size of the value Dim val: val=Inputbox("Enter value for val: ") val_length =Len(val) msgbox "Size of "&val&" is "&val_length
2) Read a value and find whether the value is numeric or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsNumeric(val) If val_type = true Then msgbox "val is Numeric"
else msgbox "val is not Numeric" End If 3)'Read a value and find whether the value is Date type data or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsDate(val) If val_type = true Then msgbox "val is Date type data" else msgbox "val is not date type" End If
4)Read a value and Verify whether the value is 10-digit number or not and started with 9 0r 8. 'Then Display it is a valid mobile number Dim val,val_Length, val_Numeric, val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then msgbox val&" is a valid mobile number " Else msgbox val&" is not a valid mobile number " End If 5) 'Read a mobile number and verify the series 'if it starts with 92478 or 92471 then display it is TataIndicom number 'if it starts with 98490 or 98480 then display it is Airtel number Dim val, val_Length,val_Numeric,val_Series,val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) val_Series=Left(val,5) If val_Numeric=true Then If val_Length=10 and val_Start=9 Then If val_Series = 92478 or val_Series=92471 Then msgbox "It is TataIndicom Number" ElseIf val_Series=98490 or val_Series = 98480 then msgbox "It is Airtel Number" End If Else msgbox val&" is not a valid mobile number " End If Else msgbox val& " is Invalid data" End If 6) Read a Value and Verify weather the value is started with Alfa bytes or not? (First letter should be Alfa byte) Dim val, val_Asc
val=Inputbox("enter a value") val_Asc=Asc(val) Msgbox val_Asc If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then msgbox val&" is an Alphabet" Else msgbox val&" is not an Alphabet" End If 7) Read a value and Verify weather the value is Alfa bytes are not? Dim str, valAsc, flag,i Dim strlen, counter,valsingle counter=0 str=Inputbox("enter a string value") strlen= Len(str) For i=1 to strlen step 1 valsingle=Mid(str,i,1) valAsc=Asc(valsingle) If valAsc>=65 and valAsc<=90 or valAsc>=97 and valAsc<=122Then flag=1 counter=counter+1 Else flag=0 End If Next msgbox "No.of characters " &counter If counter=strlen and flag=1Then msgbox str&" is an Alphabetic value" Else msgbox str&" is not an Alphabetic value" End If
File System Operations File System Object Model: The File System Object (FSO) model provides an object-based tool for working with folders and files. It allows us to use the familiar object. method syntax with a rich set of properties, methods, and events to process folders and files. We can also employ the traditional Visual Basic statements and commands. The FSO model gives our application the ability to create, alter, move, and delete folders, or to determine if and where particular folders exist. It also enables us to get information about folders, such as their names and the date they were created or last modified. The FSO model makes processing files much easier as well. When processing files, our primary goal is to store data in an efficient, easy-to-access format. We need to be able to create files, insert and change the data, and output (read) the data. Although we can store data in a database, doing so adds a significant amount of overhead to our application. We may not want to
have such overhead, or our data access requirements may not call for the extra functionality associated with a full-featured database. In this case, storing our data in a text file or binary file is the most efficient solution. The FSO model, contained in the Scripting type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object; however, the FSO model does not support binary files. To manipulate binary files, use the FileOpen Function with the Binary keyword. FileSystemObject Main object. Contains methods and properties that allow you to create, delete, gain information about, and generally manipulate drives, folders, and files. Many of the methods associated with this object duplicate those in other FSO objects; they are provided for convenience. Drive Object This Object Contains methods and properties that allow you to gather information about a drive attached to the system, such as its share name and how much room is available. Note that a "drive" isn't necessarily a hard disk, but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the system; it can be also be logically connected through a network.
Folder Object This Object contains methods and properties that allow you to create, delete, or move folders. Also allows you to query the system for folder names, paths, and various other properties. TextStream Object This Object allows you to read and write text files. Examples: 1) Read Content from a text file and Write in another text file Dim objFso, myFile1, myFile2, x Set objFso=createobject("Scripting.Filesystemobject") Set myFile1=objFso.opentextfile("C:\Documents and Settings\gcr\Desktop\gcreddy.txt",1) Set myFile2=objFso.createtextfile("C:\Documents and Settings\gcr\Desktop\gcrqtp.txt",1) Do Until myFile1.AtEndOfStream=True x=myFile1.Readline myFile2.Writeline x Loop myFile1.Close myFile2.Close Set objFso=Nothing 2) Read Numbers only from a text file and export to another text file Dim objFso, objTextStream, myText, x set objFso=createobject("Scripting.Filesystemobject") set objTextStream=objFso.opentextfile("C:\Documents and Settings\gcr\Desktop\gcreddy.txt",1) Set objTextStream2=objFso.opentextfile("C:\Documents and Settings\gcr\Desktop\gcrqtp.txt",2) objTextStream2.WriteLine "Numbers" objTextStream2.WriteLine "---------" Do Until objTextStream.AtEndOfStream myText=objTextStream.ReadLine x=split(myText," ") For i=lbound(x) to ubound(x)
If isnumeric(x(i)) =True Then objTextStream2.WriteLine x(i) End if Next Loop objTextStream.Close objTextStream2.Close Set objFso=Nothing
File System Scripts 1) Create a Folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.CreateFolder(strDirectory) 2) Delete a Folder Set oFSO = CreateObject("Scripting.FileSystemObject") oFSO.DeleteFolder("E:\Gcreddy") 3) Copying Folders Set oFSO=createobject("Scripting.Filesystemobject") oFSO.CopyFolder "E:\gcr", "C:\jvr", True 4) Checking weather the folder available or not, if not creating the folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FolderExists(strDirectory) Then Set objFolder = objFSO.GetFolder(strDirectory) msgbox strDirectory & " already created " else Set objFolder = objFSO.CreateFolder(strDirectory) end if 5) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.FileSystemObject") Set colDrives = oFSO.Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.DriveLetter Next
6) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.FileSystemObject") Set oDrive = oFSO.GetDrive("C:") MsgBox "Available space: " & oDrive.AvailableSpace
Flat File Scripts Computer File System It is a feature of the Operating System, used to Create/Modify/view/delete Drives, Folders and Files OS Distribution Operating System and Other Utilities FileSystemObject VBScript has Provided FileSystemObject to perform file system operations through scripting Dim objFso 'Creating an Automation Object in File System class, that can be used to perform Operations on Computer File System Set objFso=CreateObject("scripting.FileSystemObject") 1) Creating a File Dim objFso Set objFso=CreateObject("scripting.FileSystemObject") objFso.CreateTextFile ("E:\Gcreddy.txt") objFso.CreateTextFile ("E:\Gcreddy.doc") objFso.CreateTextFile ("E:\Gcreddy.xls") objFso.CreateTextFile ("E:\Gcreddy.pdf") Note: We can Create other files also, but they act as Text/Flat Files Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt") 2) Checking weather the File is available or not, if not creating the File strDirectory="E:\" strFile="Gcreddy.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt") End if 3) Reading Data character by character from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Read(1) msgbox strCharacters Loop 4) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Readline msgbox strCharacters Loop
5) Data Driven Testing by fetching Test data directly from a Text file. ************************************************** 'Test Requirement: Data Driven Testing by Fetching Test data directly from a Text file. 'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requisites: 'gcr.txt (Test Data) 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Read the Data & Split the Data 'Generating the Login Operation 'Pass Parameters '************************************************* Dim objFso, myFile, myLine, myField Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2Write & 8-Append myFile.SkipLine Do Until myFile.AtEndOfStream myLine=myFile.ReadLine myField=Split(myLine,",") SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0) Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1) wait 2 Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Loop myFile.Close Set objFso=Nothing 6) Writing data to a text file Dim Stuff, myFSO, WriteStuff, dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting.FileSystemObject") Set WriteStuff = myFSO.OpenTextFile("e:\Gcreddy.txt", 8, True) WriteStuff.WriteLine(Stuff) WriteStuff.Close SET WriteStuff = NOTHING SET myFSO = NOTHING 7) Delete a text file Set objFSO=createobject("Scripting.filesystemobject") Set txtFilepath = objFSO.GetFile("E:\gcr.txt") txtFilepath.Delete() 8) Checking weather the File is available or not, if available delete the File strDirectory="E:\"
strFile="gcr.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFile = objFSO.Getfile(strDirectory & strFile) objFile.delete () End if 9) Comparing two text files Dim f1, f2 f1="e:\Gcreddy1.txt" f2="e:\Gcreddy2.txt" Public Function CompareFiles (FilePath1, FilePath2) Dim FS, File1, File2 Set FS = CreateObject("Scripting.FileSystemObject") If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then CompareFiles = True Exit Function End If Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0) Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0) CompareFiles = False Do While File1.AtEndOfStream = False Str1 = File1.Read Str2 = File2.Read CompareFiles = StrComp(Str1, Str2, 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1.Close() File2.Close() End Function Call Comparefiles(f1,f2) If CompareFiles(f1, f2) = False Then MsgBox "Files are identical." Else MsgBox "Files are different." End If 10) Counting the number of times a word appears in a file sFileName="E:\gcr.txt" sString="gcreddy" Const FOR_READING = 1 Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches Set oFso = CreateObject("Scripting.FileSystemObject") Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING) sReadTxt = oTxtFile.ReadAll Set oRegEx = New RegExp oRegEx.Pattern = sString oRegEx.IgnoreCase = bIgnoreCase oRegEx.Global = True Set oMatches = oRegEx.Execute(sReadTxt) MatchesFound = oMatches.Count Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound 11) Read a CSV File Using Database Techniques On Error Resume Next
Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") strPathtoTextFile = "C:\Databases\" objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & strPathtoTextFile & ";" & _ "Extended Properties=""text;HDR=YES;FMT=Delimited""" objRecordset.Open "SELECT * FROM PhoneList.csv", _ objConnection, adOpenStatic, adLockOptimistic, adCmdText Do Until objRecordset.EOF Wscript.Echo "Name: " & objRecordset.Fields.Item("Name") Wscript.Echo "Department: " & _ objRecordset.Fields.Item("Department") Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension") objRecordset.MoveNext Loop 12) Read a Text File into an Array Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("e:\gcreddy.txt", ForReading) Do Until objTextFile.AtEndOfStream strNextLine = objTextFile.Readline arrServiceList = Split(strNextLine , ",") Wscript.Echo "Server name: " & arrServiceList(0) For i = 1 to Ubound(arrServiceList) Wscript.Echo "Service: " & arrServiceList(i) Next Loop 13) 'Calculate size of a Text file Dim objFso, File1,File2 File1="C:\Documents and Settings\1 RIGHATWAY\Desktop\xyz.txt" Set objFso=CreateObject(" Scripting.FileSystemObject") x= objFso.GetFile(File1).Size Msgbox x& " Bytes" 14) 'Test Requirement: Open 1 to 10 orders in Flight Reservation , Capture Customer names and Export into a Text file 'Test Flow: 'Login Operation 'Open Order Operation and form the Loop to open 1 to 10 Orders 'Capture Cusomer names using GetROProperty Method 'Create File system Object and Open the Text file using the Object and Export Cusomer names '---------------------------------------------------------------------------Option Explicit Dim Order_Number, Customer_Name, objFso, myFile Set objFso=CreateObject("Scripting.FileSystemObject")
Set myFile= objFso.CreateTextFile ("C:\Documents and Settings\1 RIGHATWAY\Desktop\abcNew.txt",2) myFile.WriteLine "Cusomer Names" myFile.WriteLine "--------------------" If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "asdf" Dialog("Login").WinEdit("Password:").SetSecure "4c48590870466b8dc050bbd24e816890c747ccf8" Dialog("Login").WinButton("OK").Click End If For Order_Number= 1 to 10 step 1 Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click Customer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text") wait (2) myFile.WriteLine Customer_Name Next myFile.Close Set objFso=Nothing 15) '****************************************************** 'Test Requirement: Capturing all Buttons Names from the Login Dialog box and exporting to a Text file 'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requasites: 'gcr.txt 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Creating Collection object and Capturing Button Names using the Object 'Writing Button Names to an External Text file '******************************************************** Dim objFso, myFile, oButton, Buttons, TotButtons Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",2) '1 for Read, 2Write & 8-Append myFile.WriteLine "Button Names" myFile.WriteLine "----------" Set oButton=Description.Create oButton("micclass").value="WinButton" SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Set Buttons=Dialog("text:=Login").ChildObjects(oButton) TotButtons=Buttons.Count For i= 0 to TotButtons-1 myButton=Buttons(i).GetRoProperty("text") myFile.WriteLine myButton Next myFile.Close Set objFso=Nothing
16) Delete a Text file if it is an empty file Dim objFso, FilePath FilePath="C:\Documents and Settings\gcreddy\Desktop\abc.txt" Set objFso=CreateObject("Scripting.FileSystemObject") FileSize=objFso.GetFile(FilePath).Size 'Msgbox FileSize If FileSize=0 Then objFso.DeleteFile(FilePath) End If Set objFso=Nothing
Database Scripts Database Scripts-I 1) Get Test Data From a Database and use in Data Driven Testing (through Scripting) Dim objCon, objRs 'Creating an automation object in database connection class, it is used for connecting to databases. Set objCon=CreateObject("Adodb.Connection") 'Creating an automation object in database record set class, it is used for performing operations on database tables(records). Set objRs= CreateObject("Adodb.Recordset") 'Establishing connection string for Ms-Access database. objCon.Provider=("Microsoft.Jet.oledb.4.0") objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Flights.mdb" objRs.Open "Select * from Login", objCon Do Until objRs.EOF=True SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set objRs.Fields("Agent") Dialog("Login").WinEdit("Password:").Set objRs.Fields("Pwd") Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close objRs.MoveNext Loop objRs.Close objCon.Close Set objCon=Nothing Set objRs=Nothing 2) Exporting Data from a Database to an Excel Sheet 1) Dim con,rs 2) Set con=createobject("adodb.connection") 3) Set rs=createobject("adodb.recordset") 4) con.provider="microsoft.jet.oledb.4.0" 5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.mdb" 6) rs.open"select*from Login",con 7) Set ex=createobject("Excel.Application") 8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My Documents\Gcreddy.xls") 9) Set b=a.worksheets("sheet1") 10) i=1 11) Do While Not rs.EOF 12) b.cells (i,1).value=rs.fields("agent") 13) b.cells(i,2).value=rs.fields("password")
14) rs.movenext 15) i=i+1 16) Loop 17) a.save 18) a.close 3) Exporting Data from a Database to a Text file Dim objCon,objRs,ObjFso,myFile,myData,rc,r Set objCon=createobject("Adodb.connection") Set objRs=createobject("Adodb.Recordset") set objFso=createobject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\My Documents\gcreddy.txt",8) objcon.provider=("Microsoft.jet.oledb.4.0") objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb" objrs.open "select * from login",objCon r=1 Do until objRs.EOF a=objRs.Fields ("Agent") b=objRs.Fields ("Pwd") myFile.Writeline a &","& b r=r+1 objRs.MoveNext Loop myFile.Close objCon.Close 4) Connecting to a SQL Sever database Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider=SQLOLEDB;Data Source=atl-sql-01;" & _ "Trusted_Connection=Yes;Initial Catalog=Northwind;" & _ "User ID=fabrikam\kenmyer;Password=34DE6t4G!;" objRecordSet.Open "SELECT * FROM Customers", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst Wscript.Echo objRecordSet.RecordCount 5) Open a Database Using a DSN Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Northwind;fabrikam\kenmyer;34ghfn&!j" objRecordSet.Open "SELECT * FROM Customers", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount 6) Open Two Recordsets Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") Set objRecordSet2 = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider= Microsoft.Jet.OLEDB.4.0; " & _ "Data Source=inventory.mdb" objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet2.MoveFirst Do Until objRecordset.EOF Wscript.Echo objRecordset.Fields.Item("ComputerName") Wscript.Echo objRecordset.Fields.Item("OSName") objRecordSet.MoveNext Loop Do Until objRecordset2.EOF Wscript.Echo objRecordset2.Fields.Item("DriveName"), _ objRecordset2.Fields.Item("DriveDescription") objRecordSet2.MoveNext Loop objRecordSet.Close objRecordSet2.Close objConnection.Close
7) Searching a Database Using String Criteria Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider = Microsoft.Jet.OLEDB.4.0; " & _ "Data Source = eventlogs.mdb" objRecordSet.Open "SELECT * FROM EventTable " & _ "WHERE Type = 'Error'", objConnection, adOpenStatic, _ adLockOptimistic
Database Scripts-II Database Scripts-II 1) Insert Data into a database table using Database Command Object Dim objCon,objCom Set objCon=Createobject("ADODB.connection") objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;" Set objCom=Createobject("ADODB.Command") objCom.ActiveConnection=objCon objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)" objCom.Execute objCon.Close Set objCom=Nothing Set objCon=Nothing 2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i Set objCon=Createobject("ADODB.connection") objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;" Set objCom=Createobject("ADODB.Command") objCom.ActiveConnection=objCon Datatable.AddSheet("input") Datatable.ImportSheet "C:\gcreddy.xls",1,"input" intRowcount=Datatable.GetSheet("input").GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.SetCurrentRow(i) strEmpName= DataTable.Value(1,"input") intEmpNo= DataTable.Value(2,"input") intEmpSal= DataTable.Value(3,"input") objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")" objCom.Execute Next objCon.Close Set objCom=Nothing Set objCon=Nothing 3) Fetch data from a database, and compare with expected data in Excel file. ---------Dim objCon, objRs, objExcel, myFile, mysheet Set objCon=CreateObject("Adodb.Connection")
Set objRs= CreateObject("Adodb.Recordset") Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\TestData2.xls") Set mySheet=myFile.Worksheets("Sheet1") Rc=mySheet.usedrange.rows.count 'Msgbox Rc objCon.Provider=("Microsoft.Jet.oledb.4.0") objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Comp.mdb" objRs.Open "Select EMPName from Employee", objCon
Do Until objRs.EOF=True x=objRs.Fields("EMPName") For j= 2 to Rc y=mySheet.cells(j,"A") If x=y Then Reporter.ReportEvent micPass,"Res","Name: "& y &" Available" ' Else 'Reporter.ReportEvent micFail,"Res","Name: "& y &" Not Available" End If Next objRs.MoveNext Loop objExcel.Quit Set objExcel=Nothing objRs.Close objCon.Close Set objRs=Nothing Set objCom=Nothing
QTP Scripting
QTP Database Script Examples ----------------------------------------------------------------------------1) Data Driven Testing for Login Operation by Fetching Test Data directly From a Database Option Explicit Dim objConnection, objRecordSet 'Creating an Automation Object in Database Connection Class, that can be used to connect to Databases Set objConnection=CreateObject("Adodb.Connection") 'Creating an Automation Object in Database RecordSet Class, that can be used to Perform Operations on Database Tables (Records) Set objRecordSet=CreateObject("Adodb.RecordSet") 'Establishing Connection String for MS Access Database objConnection.Provider=("Microsoft.Jet.OLEDB.4.0") objConnection.Open "C:\Documents and Settings\bannu\Desktop\gcreddy.mdb" 'Fetching Test Data using RecordSet Object objRecordSet.Open "Select * From Login",objConnection Do Until objRecordSet.EOF=True SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").Winedit("attached text:=Agent Name:").Set objRecordSet.Fields("Agent") Dialog("text:=Login").Winedit("attached text:=Password:").Set objRecordSet.Fields("Password")
Wait 2 Dialog("text:=Login").Winbutton("text:=OK","width:=60").Click Window("text:=Flight Reservation").Close objRecordSet.MoveNext Loop objRecordSet.Close objConnection.Close Set objRecordSet=Nothing Set objConnection=Nothing 2) Write Data to a Database Table Dim objConnection, objCommand Set objConnection=CreateObject("Adodb.Connection") Set objCommand=CreateObject("Adodb.Command") objConnection.Provider=("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objCommand.ActiveConnection=objConnection objCommand.CommandText ="Insert into Login values (8,'Chennai','Mercury')" objCommand.Execute objConnection.Close Set objCommand=Nothing Set objConnection=Nothing ----------------------------------------------------3) Write Multiple Sets of Data to a Database Table Dim objConnection, objCommand Dim objExcel, objWorkBook, objWorksheet Set objExcel=CreateObject("Excel.Application") Set objWorkBook=objExcel.Workbooks.Open ("C:\Documents and Settings\Test class\Desktop\data1.xls") Set objWorkSheet=objWorkBook.Worksheets("Sheet1") Set objConnection=CreateObject("Adodb.Connection") Set objCommand=CreateObject("Adodb.Command") objConnection.Provider=("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objCommand.ActiveConnection=objConnection Rows_Count=objWorkSheet.Usedrange.Rows.Count For i= 2 To Rows_Count Step 1 SNO=objWorkSheet.Cells(i,"A") Agent=objWorkSheet.Cells(i,"B") Password=objWorkSheet.Cells(i,"C") objCommand.CommandText ="Insert into Login values ('"&SNO&"','"&Agent&"','"&Password&"')" objCommand.Execute Next objWorkBook.Close objExcel.Quit Set objExcel=Nothing objConnection.Close Set objCommand=Nothing Set objConnection=Nothing ---------------------------------------------------------
4) Export Data from a Database Table to an Excel file (2nd Sheet) Option Explicit Dim objConnection, objRecordset Dim objExcel, objWorkbook, objWorksheet, i Set objConnection = Createobject ("Adodb.Connection") Set objRecordset = Createobject ("Adodb.Recordset") Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:\Documents and Settings\Test class\Desktop\data1.xls") Set objWorksheet = objWorkbook.Worksheets("Sheet2") objWorksheet.cells(1,"A") = "Agents" objWorksheet.cells(1,"B") = "Password" objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objRecordset.Open "Select Agent, Password from Login", objConnection i = 2 'Rows Do Until objRecordset.EOF objWorksheet.cells(i, "A") = objRecordset.Fields("Agent") objWorksheet.cells(i, "B") = objRecordset.Fields("Password") i=i+1 objRecordset.MoveNext Loop objWorkbook.Save objWorkbook.Close objExcel.Quit Set objExcel = Nothing objRecordset.Close objConnection.Close Set objRecordset = Nothing Set objConnection = Nothing ---------------------------------------------------5) Export Data from a Database Table to a Text file Option Explicit Dim objConnection, objRecordset Dim objFso,myFile Set objConnection = Createobject ("Adodb.Connection") Set objRecordset = Createobject ("Adodb.Recordset") Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\data1.txt",2) myFile.WriteLine "Agent "&" Password" myFile.WriteLine "--------------------" objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objRecordset.Open "Select Agent, Password from Login", objConnection
Do Until objRecordset.EOF myFile.WriteLine objRecordset.Fields("Agent")&" ," & objRecordset.Fields("Password") objRecordset.MoveNext Loop myFile.Close Set objFso=Nothing objRecordset.Close objConnection.Close Set objRecordset = Nothing Set objConnection = Nothing -----------------------------------------------6) Export Data from a Text File to a Database Table Option Explicit Dim objConnection, objCommand Dim objFso,myFile,myLine,myField,SNO,Agent,Password Set objConnection = Createobject ("Adodb.Connection") Set objCommand = Createobject ("Adodb.Command") Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\dat1.txt",1) objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" myFile.SkipLine myFile.SkipLine Do While myFile.AtEndOfStream = FALSE myLine = myFile.ReadLine myField = Split(myLine,",") SNO = myField(0) Agent = myField(1) Password = myField(2) objCommand.ActiveConnection = objConnection objCommand.CommandText = "Insert into Login2 values('"&SNO&"','"&Agent&"','"&Password&"')" objCommand.Execute Loop myFile.Close Set objFso=Nothing Set objCommand = Nothing objConnection.Close Set objConnection = Nothing
Excel Scripts 1) Create an Excel file, enter some data and save the file through VB script? 1) Dim objexcel 2) Set objExcel = createobject("Excel.application")
3) objexcel.Visible = True 4) objexcel.Workbooks.add 5) objexcel.Cells(1, 1).Value = "Testing" 6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls") 7) objexcel.Quit 2) Check if the Excel file exists or not, if exists open the file and enter some data , If not Exists create the file and enter some data and save the file through VB script? Dim objExcel, FilePath FilePath="C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcr.xls" Set objExcel=CreateObject("Excel.Application") set objFso=CreateObject("Scripting.FileSystemObject") objExcel.Visible=True If Not objFso.FileExists(FilePath) Then objExcel.Workbooks.Add objExcel.Cells(1,1).value="QTP" objExcel.ActiveWorkbook.SaveAs (FilePath) Else set myFile= objExcel.Workbooks.Open (FilePath) Set mySheet=myFile.Worksheets("Sheet1") mySheet.cells(1,1).value="QTP" objExcel.ActiveWorkbook.Save End If objExcel.Quit Set objExcel=Nothing 3) Data Driven Testing through an External Excel Sheet 1) Set myExcel=Createobject("Excel.Application") 2) Set myFile=myExcel.workbooks.open ("C:\Documents and Settings\admin\My Documents\gcreddy.xls") 3) Set mySheet=myFile.worksheets("Sheet1") 4) Rows_Count=mySheet.usedrange.rows.count 5) For i= 1 to Rows_Count 6) Agent=mySheet.cells(i,"A") 7) pwd=mySheet.Cells(i,"B") 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set Agent 11) Dialog("Login").WinEdit("Password:").SetSecure pwd 12) Dialog("Login").WinEdit("Password:").Type micReturn 13) Window("Flight Reservation").Close 14) Next 4) Compare two excel files Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook1= objExcel.Workbooks.Open("E:\gcreddy1.xls") Set objWorkbook2= objExcel.Workbooks.Open("E:\gcreddy2.xls") Set objWorksheet1= objWorkbook1.Worksheets(1) Set objWorksheet2= objWorkbook2.Worksheets(1) For Each cell In objWorksheet1.UsedRange If cell.Value <> objWorksheet2.Range(cell.Address).Value Then msgbox "value is different" Else
msgbox "value is same" End If Next objWorkbook1.close objWorkbook2.close objExcel.quit set objExcel=nothing 5) Data Driven Testing using Data Table methods Datatable.AddSheet "gcreddy" Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.xls",1,3 n=datatable.GetSheet (3).GetRowCount For i= 1 to n Datatable.SetCurrentRow(i) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set datatable("agent",3) Dialog("Login").WinEdit("Password:").Set datatable("pwd",3) Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Next Example 2): Datatable.AddSheet "gcreddy" Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.xls",1,3 n=datatable.GetSheet (3).GetRowCount For i= 1 to n Datatable.SetCurrentRow(i) VbWindow("Form1").Activate VbWindow("Form1").VbEdit("val1").Set datatable("V1",3) VbWindow("Form1").VbEdit("val2").Set datatable("V2",3) VbWindow("Form1").VbButton("ADD").Click eres= Datatable.Value ("res",3) ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text") If eres=ares Then datatable("res",3)=pass else datatable("res",3)=fail End If Next 6) Open an Excel Spreadsheet Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\gcreddy.xls") 7) Read an Excel Spreadsheet Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open _ ("C:\Scripts\New_users.xls") intRow = 2 Do Until objExcel.Cells(intRow,1).Value = "" Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).Value Wscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).Value
Wscript.Echo "LastName: " & objExcel.Cells(intRow, 4).Value intRow = intRow + 1 Loop objExcel.Quit 8) Add Formatted Data to a Spreadsheet Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.Add objExcel.Cells(1, 1).Value = "Test value" objExcel.Cells(1, 1).Font.Bold = TRUE objExcel.Cells(1, 1).Font.Size = 24 objExcel.Cells(1, 1).Font.ColorIndex = 3 9) Sort an Excel Spreadsheet on Three Different Columns Const xlAscending = 1 Const xlDescending = 2 Const xlYes = 1 Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook = _ objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls") Set objWorksheet = objWorkbook.Worksheets(1) Set objRange = objWorksheet.UsedRange Set objRange2 = objExcel.Range("A1") Set objRange3 = objExcel.Range("B1") Set objRange4 = objExcel.Range("C1") objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _ objRange4,xlDescending,xlYes 10) Short an excel sheet column Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook = objExcel.Workbooks.Add Set objWorksheet = objWorkbook.Worksheets(1) objExcel.Cells(1, 1).Value = "5" objExcel.Cells(2, 1).Value = "1" objExcel.Cells(3, 1).Value = "0" objExcel.Cells(4, 1).Value = "3" Set objRange=objworksheet.usedrange objrange.sort(objrange) 11) Add New Sheet to Excel File Dim objExcel Set objExcel = createobject("Excel.Application")
objExcel.Visible=True objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls") objExcel.Worksheets.Add objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing 12) Rename Sheets in an Excel File (WorkBook) Dim objExcel Set objExcel = createobject("Excel.Application") objExcel.Visible=True objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls") objExcel.Worksheets("Sheet1").Name="gcr" objExcel.Worksheets("Sheet2").Name="qtp" objExcel.Worksheets("Sheet3").Name="training" objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing 13) Add a Sheet to an Excel File (WorkBook) and change the Position Dim objExcel Set objExcel = createobject("Excel.Application") objExcel.Visible=True Set myFile= objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls") objExcel.Worksheets.Add myFile.Sheets("Sheet4").Move, myFile.Sheets(4) objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing
QTP Scripts examples 1) Verify Login Boundary (Check all the boundary conditions of the Login dialog box. Checks to see if the correct message appears in the error window (Flight Reservation Message) 1) ApplicationDir = Environment("ProductDir") 2) ApplicationPath = "\samples\flight\app\flight4a.exe" 3) If Window("Flight Reservation").Exist(2) Then 4) Window("Flight Reservation").Close 5) SystemUtil.Run ApplicationDir & ApplicationPath 6) Elseif Not Dialog("Login").Exist(1) Then 7) SystemUtil.Run ApplicationDir & ApplicationPath 8) End If 9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value ("AgentName",dtGlobalSheet) 10) Dialog("Login").WinEdit("Password:").Set Datatable.Value ("Password",dtGlobalSheet) 11) Dialog("Login").WinButton("OK").Click 12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and Datatable.Value ("Status",dtGlobalSheet)="Fail" Then 13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").Check CheckPoint("Agent name must be at least 4 characters long.") 14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click 15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value ("Status",dtGlobalSheet)="Pass" Then
16) Reporter.ReportEvent PASS,"Login: ","Succeeded" 17) Else 18) Reporter.ReportEvent Fail,"Login: ","Combination #" & Datatable.GetCurrentRow & " was not according to Excel file" 19) End If 2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.) 1) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 2) Dialog("Login").Activate 3) Dialog("Login").WinButton("Cancel").Click 4) If Dialog("Login").Exist (2) =True Then 5) Reporter.ReportEvent 1,"sd","Fail" 6) Else 7) Reporter.ReportEvent 0,"sd","Pass" 8) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 9) End If 10) Dialog("Login").Activate 11) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 12) Dialog("Login").WinButton("Cancel").Click 13) If Dialog("Login").Exist (2) =True Then 14) Reporter.ReportEvent 1,"sd","Fail" 15) Else 16) Reporter.ReportEvent 0,"sd","Pass" 17) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 18) End If 19) Dialog("Login").Activate 20) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 21) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 22) Dialog("Login").WinButton("Cancel").Click 23) If Dialog("Login").Exist (2)=True Then 24) Reporter.ReportEvent 1,"sd","Fail" 25) Else 26) Reporter.ReportEvent 0,"sd","Pass" 27) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 28) End If 29) Dialog("Login").Activate 30) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 31) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 32) Dialog("Login").WinButton("OK").Click 3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application. 1) Dim aRes,sRes,dRes,mRes 2) VbWindow("VbWindow").Activate 3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10" 4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20" 5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text") 6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text") 7) VbWindow("VbWindow").VbButton("ADD").Click 8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 9) VbWindow("VbWindow").VbButton("SUB").Click 10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 11) VbWindow("VbWindow").VbButton("MUL").Click 12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 13) VbWindow("VbWindow").VbButton("DIV").Click 14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 15) v1=cdbl(v1) 16) v2=cdbl(v2) 17) aRes=cdbl (aRes) 18) sRes=cdbl (sRes) 19) mRes=cdbl (mRes)
20) dRes=cdbl (dRes) 21) If aRes=v1+v2 Then 22) Reporter.ReportEvent 0,"Res","Addition Passed" 23) else 24) Reporter.ReportEvent 1,"Res","Addition Failed" 25) End If 26) If sRes=v1-v2 Then 27) Reporter.ReportEvent 0,"Res","Subtraction Passed" 28) else 29) Reporter.ReportEvent 1,"Res","Subtraction Failed" 30) End If 31) If mRes=v1*v2 Then 32) Reporter.ReportEvent 0,"Res","Multiplecation Passed" 33) else 34) Reporter.ReportEvent 1,"Res","Multiplecation Failed" 35) End If 36) If dRes=v1/v2 Then 37) Reporter.ReportEvent 0,"Res","Division Passed" 38) else 39) Reporter.ReportEvent 1,"Res","Division Failed" 40) End If 4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.) 1) Option explicit 2) Dim bo,ao 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8bce9984f1a15ea187a2da5b18c545abb01cf" 8) Dialog("Login").WinButton("OK").Click 9) End If 10) Window("Flight Reservation").Activate 11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") 17) If bo=False Then 18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled" 19) else 20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled" 21) End If 22) If ao=True Then 23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled" 24) else 25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled" 26) End If 5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price) 1) Option explicit 2) Dim n,f,b,e 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb" 8) Dialog("Login").WinButton("OK").Click
9) End If 10) For n= 1 to 10 step 1 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) Window("Flight Reservation").WinRadioButton("First").Set 17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) Window("Flight Reservation").WinRadioButton("Business").Set 19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 20) Window("Flight Reservation").WinRadioButton("Economy").Set 21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 22) f=cdbl(mid(f,2,len (f-1))) 23) b=cdbl(mid(b,2,len (b-1))) 24) e=cdbl(mid(e,2,len (e-1))) 25) If f=3*e and b=2*e Then 26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there" 27) else 28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there" 29) End If 30) Window("Flight Reservation").WinButton("Button_2").Click 31) Window("Flight Reservation").Dialog("Flight Reservations").WinButton("No").Click 32) Next 6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price) 1) Option Explicit 2) Dim t,p,tot,n 3) For n= 1 to 10 step 1 4) If Not window("Flight Reservation").Exist (2) Then 5) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" 6) Dialog("Login").Activate 7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 8) Dialog("Login").WinEdit("Password:").SetSecure "4aa892d62c529f1c23298175ad78c58f43da8e34" 9) Dialog("Login").WinButton("OK").Click 10) End If 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText 17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText 19) t=cdbl (t) 20) p=Cdbl(mid(p,2,len (p-1))) 21) tot=Cdbl(mid(tot,2,len (tot-1))) 22) If tot=t*p Then 23) Reporter.ReportEvent 0,"Res","Calculation Passed" 24) else 25) Reporter.ReportEvent 1,"Res","Calculation Failed" 26) End If 27) Next 7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.) 1) Option explicit
2) Dim qtp,flight_app,f,t,i,j,x,y 3) If Not Window("text:=Flight Reservation").Exist (7)= True Then 4) QTP=Environment("ProductDir") 5) Flight_app="\samples\flight\app\flight4a.exe" 6) SystemUtil.Run QTP & Flight_app 7) Dialog("text:=Login").Activate 8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf" 9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure "4aa5ed3daf680e7a759bee1c541939d3a54a5b65" 10) Dialog("text:=Login").WinButton("text:=OK").Click 11) End If 12) Window("text:=Flight Reservation").Activate 13) Window("text:=Flight Reservation").WinButton("window id:=6").Click 14) Window("text:=Flight Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type "090910" 15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetItemsCount 16) For i= 0 to f-1 step 1 17) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").Select (i) 18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetROProperty ("text") 19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetItemsCount 20) For j= 0 to t-1 step 1 21) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").Select (j) 22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetROProperty ("text") 23) If x <> y Then 24) Reporter.ReportEvent 0,"Res","Test Passed" 25) Else 26) Reporter.ReportEvent 1,"Res","Test Failed" 27) End If 28) Next 29) Next 8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate 9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a" 12) ord=Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").GetVisibleText 13) If ord= "a" Then 14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data" 15) else 16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 18) End If 9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting) 1) Dim fso,myfile 2) Set fso=createobject("scripting.filesystemobject") 3) Set myfile= fso.opentextfile ("F:\gcr.txt",1) 4) myfile.skipline 5) While myfile.atendofline <> True 6) x=myfile.readline 7) s=split (x, ",") 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set s(0)
11) Dialog("Login").WinEdit("Password:").SetSecure s(1) 12) Dialog("Login").WinButton("OK").Click 13) Window("Flight Reservation").Close 14) Wend 10) Count, how many Buttons and Edit boxes available in Flight Reservation main window. 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").Set "mercury" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Set oDesc = Description.Create() 9) oDesc("micclass").Value = "WinButton" 10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc) 11) Num_Buttons = Buttons.Count() 12) Set oDesc1=Description.Create() 13) oDesc1("micclass").Value="WinEdit" 14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1) 15) Num_Editboxes= editboxes.count () 16) sum= Num_Buttons+Num_Editboxes 17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes 11) Verify search options in Open Order Dialog box (After selecting open order, 3 search options should be enabled and not checked, After selecting Order No option, other options should be disabled, After selecting Customer Name, Flight date option enabled and Order No disabled After selecting Flight date option, Customer Name enabled and Order No disabled) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate 9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").Activate 11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 12) ce=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Enabled") 14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 15) cc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked") 16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Checked") 17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and fc="OFF") Then 18) Reporter.ReportEvent 0,"Res","Pass" 19) else 20) Reporter.ReportEvent 1,"Res","Fail" 21) End If 22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 23) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 24) If ono="ON" Then 25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 26) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 27) fd=false 28) ono=false 29) Reporter.ReportEvent 0,"Res","Pass" 30) else
31) Reporter.ReportEvent 1,"Res","Fail" 32) End If 33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "OFF" 34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON" 35) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked") 36) If cn="ON" Then 37) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 39) fd=True 40) ono=false 41) Reporter.ReportEvent 0,"Res","Pass" 42) else 43) Reporter.ReportEvent 1,"Res","Fail" 44) End If 45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "OFF" 46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").Set "ON" 47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Checked") 48) If fd="ON" Then 49) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 50) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 51) cn=True 52) ono=false 53) Reporter.ReportEvent 0,"Res","Pass" 54) else 55) Reporter.ReportEvent 1,"Res","Fail" 56) End If 12) In Login Dialog box, Verify Help message (The message is The password is 'MERCURY') 1) If Not Dialog("Login").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) End If 4) Dialog("Login").Activate 5) Dialog("Login").WinButton("Help").Click 6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password is 'MERCURY'").GetROProperty("text") 7) If message="The password is 'MERCURY'" Then 8) Reporter.ReportEvent 0,"Res","Correct message "&message 9) else 10) Reporter.ReportEvent 1,"Res","Worng message " 11) End If
Web Scripts 1) Count all opened Browsers on desktop and close them all? Set oDesc = Description.Create() oDesc("micclass").Value = "Browser" Set Browsers =Desktop.ChildObjects (oDesc) NumberofBrowsers = Browsers.Count() Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsers For Counter=0 to NumberofBrowsers-1 Browsers(Counter).Close Next 2) Count, how many links available in Mercury Tours Home Page. Set oDesc = Description.Create() oDesc("micclass").Value = "Link" Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc)
NumberOfLinks = Lists.Count() Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks 3) Verify whether the 'Gmail' link available or not on Google Homepage Option explicit Dim oLink, Links, TotLinks, i, myLink Set oLink = description.Create oLink("micclass").value = "Link" SystemUtil.Run "D:\Program Files\Internet Explorer\IEXPLORE.EXE" set Links = Browser("name:=Google").page("title:=Google").ChildObjects(oLink) TotLinks = Links.count For i =0 to TotLinks-1 myLink = Links(i).getroproperty("innertext") If mylink = "Gmail" Then reporter.ReportEvent 0,"res","Link Gmail available" End If Next 4) Count number of Links, Edit Boxes available on Google Homepage? Dim oLink Set oLink=description.Create Set oEdit=description.Create oLink("micclass").value="Link" oEdit("micclass").value="WebEdit" Set Links=browser("name:=Google").page("title:=Google").ChildObjects(oLink) Set EditBoxes=browser("name:=Google").page("title:=Google").ChildObjects(oEdit) TotLinks= Links.count TotEditBoxes=EditBoxes.count msgbox TotLinks msgbox TotEditBoxes Reporter.ReportEvent 0,"Result","Total Links are: "&TotLinks&"Total edit Boxes are: "&TotEditBoxes 5) Count how many links available in a Web Page(any web page, using Regular Expressions) Dim oLink,Links, TotLinks Set oLink=Description.Create oLink("micclass").value="Link" Set Links=Browser("title:=.*").page("title:=.*").ChildObjects(oLink) TotLinks=Links.count msgbox TotLinks Reporter.ReportEvent 2,"Res","Total Links are: "&TotLinks 6) Verify Cost in jjperfumes.com 'Test Flow 'i) Launch jjperfumes.com 'ii) Select a product and enter some quantity 'iii) select Add to Cart, capture Unit price, Quantity and Cost 'iV) Remove $ symbols and compare '---------------------------------- ----SystemUtil.Run "C:\Program Files\Internet Explorer\iexplore.exe","","C:\Documents and Settings\gcr.GCRC9A12FBD3D9","open" Browser("Google").Page("Google").Sync Browser("Google").Navigate "http://www.jjperfumes.com/" Browser("Google").Page("JJ Perfumes-Discount perfume").Image("thumb_1845_WLINP50PSW").Click Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebEdit("quantity").Set "4" Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebButton("Add To Cart").Click
Unit_Price = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]").GetROProperty("innertext") Qty = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebEdit("quantity[]").GetROProperty("value") Cost = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]_2").GetROProperty("innertext") Qty=Cint(Qty) Unit_Price=Cdbl (Mid (Unit_Price,3)) Cost=Cdbl (Mid (Cost, 3)) 'Msgbox Unit_Price: Msgbox Qty: Msgbox Cost If Cost=Qty * Unit_Price Then Reporter.ReportEvent micPass,"Res","Cost is Correct" Else Reporter.ReportEvent micFail,"Res","Cost is InCorrect" End If Function To Create HTML Report Dim StartTime,stTime, enTime Dim fso, ts,intCnt, intPass,intFail intPass=0 intFail=0 Const ForWriting = 2 Function OpenFile (strFileName) StartTime = Timer stTime = Time Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.OpenTextFile(strFileName,2) 'OpenFile = strFileURL CreateHeader End Function ***************************** Function To Close File Dim objIE,strFileURL Function CloseFile ( strFileURL,strEnv ) Footer(strEnv) ts.close() Set objIE = CreateObject("InternetExplorer.Application") objIE.visible = True objIE.Navigate strFileURL wait(5) Set objIE=nothing End Function *********************** Function to Clear Cookies() Function ClearCookies() SystemUtil.Run "iexplore.exe" WebUtil.DeleteCookies Set objBrowser=Description.Create objBrowser("micclass").value="Browser" Set objBCount = Desktop.ChildObjects(objBrowser) intBrowserCount = objBCount.Count strHwnd=Browser("creationtime:=" & intBrowserCount).GetROProperty("hwnd") SystemUtil.CloseProcessByHwnd(strHwnd) End Function ***********************
Function to send Email Function SendMail() If k=0 Then 'Nothing Else msgsub = " Geo_PostalCode pattern searchTest Results:" &vbcrLf &"One or more of the Test Cases Failed." &vbcrLf &"See attachment for details." End If Set objConf = CreateObject("CDO.Configuration") cdoSendUsingPort=2 sMailServerName="smtp.phx.move.com" cdoAnonymous=cdoNONE objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = sMailServerName objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoAnonymous 'cdoBasic objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "corp\ NRaoJ " 'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "123K!r45" objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60 objConf.fields.Update Set objMsg = CreateObject("CDO.Message") objMsg.Configuration = objConf objMsg.to = "[email protected]" objMsg.From = "[email protected]" objMsg.Subject = "~Geo_PostalCode pattern search" objMsg.TextBody =msgsub doc=strFilepath objMsg.AddAttachment(doc) objMsg.Send Set objMsg = Nothing NewMail = True End Function *********************** Function to create append excel Function LogFile Set objExcel=CreateObject("Excel.Application") objExcel.visible=False objExcel.workbooks.open(strFilePath) r=1 Do Until len(objExcel.cells(r,1))=0 r=r+1 Loop objExcel.cells(r,1).value="Step Name" objExcel.cells(r,2).value="Step Description" objExcel.cells(r,3).value="Test Results" objExcel.DisplayAlerts = False objExcel.Save objExcel.Quit Set objExcel = Nothing End Function *********************** Function to get the Application Environment on which the script is running
Function GetEnv() Set fso=Createobject("Scripting.FileSystemObject") sFile="C:\WINDOWS\system32\drivers\etc\hosts" Set MyFile=fso.OpenTextFile(sFile,1, True) Do sEnv=MyFile.ReadLine If instr(sEnv,"PRODUCTION")>0 Then GetEnv="Production" Exit do Elseif instr(sEnv,"Staging")>0 Then GetEnv="Staging" Exit do Elseif instr(sEnv,"QA MAINTENANCE")>0 Then GetEnv="QAM" Exit do Elseif instr(sEnv,"qap.")>0 Then GetEnv="qap" Exit do End If Loop While MyFile.AtEndOfStream=False End Function *********************** Function To Create HTML Report Dim StartTime,stTime, enTime Dim fso, ts,intCnt, intPass,intFail intPass=0 intFail=0 Const ForWriting = 2 Function OpenFile (strFileName) StartTime = Timer stTime = Time Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.OpenTextFile(strFileName,2) 'OpenFile = strFileURL CreateHeader End Function
Web Scripts-II Web Scripts-II Web Application Testing using QTP. Web forms verification, Object state verification, Database Testing and Links verification. 1) Script to get the list of links in Google and do spell check ===================================== Dim d set mw=CreateObject("Word.Application") set d=Description.Create d("micclass").value="Link" set a=Browser("Google").page("Google").childobjects(d) for i=0 to a.count-1 mw.WordBasic.filenew s=a(i).getROProperty("innertext") mw.WordBasic.insert s
if mw.ActiveDocument.Spellingerrors.count>0 then Reporter.ReportEvent 1,"Spelling","spelling error :"&s end if mw.ActiveDocument.Close(False) next mw.quit set mw=nothing 2) Script to check ON the checkboxes in yahoo mail inbox ======================================== Dim d Set d=Description.Create d("micclass").value="WebCheckBox" Set c=Browser("Inbox (17) - Yahoo! Mail").Page("Inbox (17) - Yahoo! Mail").ChildObjects(d) For i=1 to 10 c(i).set "ON" Next 3) script to select a mail having subject 'hi' or 'HI' ================================= n=Browser("yahoo").Page("yahoo").WebTable("Inbox").RowCount For i=2 to n s=Browser("yahoo").Page("yahoo").WebTable("Inbox").GetCellData(i,7) If lcase(trim(s))="hi" Then Browser("yahoo").Page("yahoo").WebCheckBox("index:="&i-1).set "ON" End If Next 4) Function to send a mail ==================== Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit Set m = Nothing Set otl = Nothing End Function Call SendMail("[email protected]","hi","This is test mail for tsting","") Adv VBScripts 5) Open Internet Explorer and navigate to yahoo mail =================================== Dim ie Set ie=CreateObject("InternetExplorer.Application") ie.Visible=True ie.Navigate "www.yahoomail.com" x=Browser("CreationTime:=0").GetROProperty("title") msgbox x 6) Function for Counting Objects from any opened web page Function Objects_Count(myObject) Dim Objects Set Objects=Description.Create Objects("micclass").value=myObject
Set Object=Browser("title:=.*").Page("title:=.*").ChildObjects(Objects) TotObjects=Object.Count Msgbox TotObjects End Function Call Objects_Count("WebButton") 7) Create script for links validation and set results into an excel file Set objDesc=Description.Create objDesc("micclass").value="Link" Set objColl=Browser("title:=.*").page("title:=.*").ChildObjects(objDesc) msgbox objColl.count Set objExcel=Createobject("Excel.application") objExcel.Visible=True objExcel.Workbooks.Add set objSheet=objExcel.ActiveSheet objSheet.cells(1,1)="LinkName" set c1=objSheet.cells(1,1) c1.font.color=vbBlue objSheet.cells(1,2)="TargetUrl" Set c2=objSheet.cells(1,2) c2.font.color=vbBlue objSheet.cells(1,3)="ActualUrl" Set c3=objSheet.cells(1,3) c3.font.color=vbBlue objSheet.cells(1,4)="Status" Set c4=objSheet.cells(1,4) c4.font.color=vbBlue For i=0 to objColl.count-37 step 1 strName=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRoProperty("name") TargetUrl=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRoProperty("url") msgbox TargetUrl Browser("title:=.*").page("title:=.*").Link("index:="&i).click wait(4) ActualUrl=Browser("title:=.*").GetRoProperty("url")
msgbox ActualUrl If instr (1,TargetUrl,ActualUrl,1) > 0 Then Reporter.ReportEvent micPass,"Link Name "&strName,"Link Validation done" objSheet.cells(i+2,1)=strName objsheet.cells(i+2,2)=TargetUrl objsheet.cells(i+2,3)=ActualUrl objsheet.cells(i+2,4)="Link Validation done" Set c5= objsheet.cells(i+2,4) c5.font.color=vbGreen Else Reporter.ReportEvent micFail,"Link Name "&strName,"Link validation fail" objSheet.cells(i+2,1)=strName objsheet.cells(i+2,2)=TargetUrl objsheet.cells(i+2,3)=ActualUrl objsheet.cells(i+2,4)="Link Validation fail" Set c5= objsheet.cells(i+2,4) c5.font.color=vbRed End If Browser("title:=.*").Back Next Set objWbook=objExcel.ActiveWorkbook objWbook.SaveAs "E:\gcreddy.xls" objExcel.Quit Set objExcel=nothing
qtp real-time script example QuickTest Professional is an Industry leading and famous Testing Tool for Functional & Regression Testing QTP uses VB Script for scripting We can use QTP Tool features as well as VB Script Flow Control statements for inserting verification points. If we want to use VB Script Flow Control statements for inserting flow control statements, then we need to define Test results. QTP has provided a facility to define Test Results, using Reporter Utility Object to define test results. Using Comments is a best practice in QTP Scripting to understand the code. Creating functions for modular code is a best practice and intelligent task in scripting /Programming. using Automation Objects is an useful task in QTP scripting using Built-in functions and regular expressions is an useful task.
QTP Scripting has several types: a) GUI scripting: using scripting for GUI based Applications b) Web scripting: Automation web based applications using vb script c) Database scripting: Using scripting for Database operations such as data comparisons and validations. d) Excel scripting: Handling and using Excel files in Test Automation Excel Scripting Examples-2 1) Data Driven Testing for Login Operation by fetching from an excel file Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents and Settings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Next myFile.Close objExcel.Quit Set objExcel=Nothing ----------------------------------------2) Data Driven Testing for Login Operation by fetching Test Data from an excel file and Export Result to the Same file Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents and Settings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click If Window("text:=Flight Reservation").Exist(12) Then Window("text:=Flight Reservation").Close Result="Login Operation Sucessful" mySheet.Cells(i,"C")=Result Else SystemUtil.CloseDescendentProcesses Result="Login Operation Failed" mySheet.Cells(i,"C")=Result End If Next myFile.Save myFile.Close objExcel.Quit Set objExcel=Nothing
-----------------------------3) 'Data Driven Testing for Login Operation by fetching Test Data from an excel file ' Export Result and Error message to the Same file ' Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents and Settings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click If Window("text:=Flight Reservation").Exist(12) Then Window("text:=Flight Reservation").Close Result="Login Operation Sucessful" mySheet.Cells(i,"C")=Result Else Error_Message = Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").GetROProperty("text") SystemUtil.CloseDescendentProcesses Result="Login Operation Failed" mySheet.Cells(i,"C")=Result mySheet.Cells(i,"D")=Error_Message End If Next myFile.Save myFile.Close objExcel.Quit Set objExcel=Nothing -----------------------------------------------------------------4) 'Open 1 to 10 Orders in Flight Reservation window and capture Order Numbers and Customer Names 'Export to an Excel File Dim objExcel,myFile,mySheet,i Set objExcel = CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents and Settings\gcreddy\Desktop\data.xls") Set mySheet = myFile.Worksheets("Sheet2") row=1 mySheet.Cells(row,"A")="OrderNo" mySheet.Cells(row,"B")="CustomerName" If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "asdf" Dialog("Login").WinEdit("Password:").SetSecure "4d0a254623fcf8d10630f10b6ca8e776fcbc0717" Dialog("Login").WinButton("OK").Click End If For i = 1 to 10 Step 1 Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set i Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Customer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text") row=row+1 mySheet.Cells(row,"A") = i mySheet.Cells(row,"B") = Customer_Name Next myFile.Save myFile.Close objExcel.Quit Set objExcel =Nothing
Network Administration System Administration 1) Getting Local Computer Information Set objComputer = CreateObject("Shell.LocalMachine") Wscript.Echo "Computer name: " & objComputer.MachineName Wscript.Echo "Shutdown allowed: " & objComputer.IsShutdownAllowed Wscript.Echo "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabled Wscript.Echo "Guest access mode: " & objComputer.IsGuestAccessMode Wscript.Echo "Guest account enabled: " & _ objComputer.IsGuestEnabled(0) Wscript.Echo "Multiple users enabled: " & _ objComputer.IsMultipleUsersEnabled Wscript.Echo "Offline files enabled: " & _ objComputer.IsOfflineFilesEnabled Wscript.Echo "Remote connections enabled: " & _ objComputer.IsRemoteConnectionsEnabled Wscript.Echo "Undock enabled: " & objComputer.IsUndockEnabled
2) Restart a Computer strComputer = "atl-dc-01" Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate,(Shutdown)}!\\" & _ strComputer & "\root\cimv2") Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem") For Each objOperatingSystem in colOperatingSystems objOperatingSystem.Reboot() Next 3) Shut Down a Computer strComputer = "." Set objWMIService = GetObject_ ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & _ strComputer & "\root\cimv2") Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem") For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Win32Shutdown(1) Next 4) Modify System Startup Delay strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colStartupCommands = objWMIService.ExecQuery _ ("Select * from Win32_ComputerSystem") For Each objStartupCommand in colStartupCommands objStartupCommand.SystemStartupDelay = 10 objStartupCommand.Put_ Next
QTP Other Topics New Features of QTP 10.0 QuickTest 10.00 now offers the following new features Centrally Manage and Share Testing Assets, Dependencies, and Versions in Quality Center 10.00 Perform Single-User Local System Monitoring While Running Your Tests Improve Portability by Saving Copies of Tests Together with Their Resource Files Call Actions Dynamically During the Test Run Develop Your Own Bitmap Checkpoint Comparison Algorithm Centrally Manage Your Work Items and ToDo Tasks in the To Do Pane Improve Test Results Analysis with New Reporting Functionality Test Standard and Custom Delphi Objects Using the Delphi Add-in and Delphi Add-in Extensibility 1. Centrally Manage and Share Testing Assets, Dependencies, and Versions in Quality Center 10.00 QuickTest Professional 10.00 has a powerful set of new Quality Center 10.00 integration capabilities for QuickTest assets.* These integration capabilities include: New resources and dependencies model for storing and managing shared assets Support for asset versioning and baselines Asset Comparison Tool for comparing versions of individual QuickTest assets and Asset Viewer for viewing an earlier version of a QuickTest asset A special tool for Quality Center administrators that upgrades all QuickTest assets to use these new features. * QuickTest assets include tests, components, application areas, and the resources associated with them, such as shared object repositories, function libraries, recovery scenarios, and external data tables. 2. Perform Single-User Local System Monitoring While Running Your Tests The new local system monitoring feature (File > Settings > Local System Monitor) enables you to monitor the local (client-side) computer resources used by the application instance you are testing during a run session. You can monitor a number of different system counters to view the effects your application has on the system. You can also define upper limits for the counters. If any of the specified counters exceed these limits, the test run will fail. Additionally, you can export the data from the System Monitor tab to a variety of file types. The results generated for the counters you monitor are displayed as a line chart in a special System Monitor tab in the Test Results window. The System Monitor tab in the Test Results window The points in the chart are synchronized with the steps in the Run Results tree. When you select a step in the tree, the (red) Current Step line jumps to the corresponding location in the chart. You can also export the data from the chart so it can be further analyzed in other programs.
Migrating QTP 9.5 version to QTP 10.00 Version 1. If the scripts are in QC we can follow below method
A. If all scripts are in Quality Center then you can simply use the "Asset Upgrade Tool for QC". There is a folder with that name on the QuickTest installation DVD. 2. If the upgrade tool doesn't work on any version earlier than v10. There is another way to upgrade those scripts from QTP 9.5 to QTP 10? A. you have to open the script in QTP 10 and save the same which is the suggested process of HP. request HP to provide a tool for this. -------------------------------------------------------------------------------From QTP help ("Convert a Set of Tests from an Older QuickTest Version to the Current Version" example in Open Method of Application object): '*********************************** 'Description: ' 'This example specifies a folder in which tests from an older QuickTest version are 'stored and then loops through each test in the folder (and its subfolders) to open 'each one and save it in the current version format. ' '********************************************* Dim qtApp 'As QuickTest.Application ' Declare the Application object variable Dim filesys Dim maindir Dim testCol Dim checkfolder ' Create the QuickTest Professional object Set qtApp = CreateObject("QuickTest.Application") qtApp.Launch qtApp.Visible = True ' Get the collection of test scripts Set filesys = CreateObject("Scripting.FileSystemObject") ' TO DO: Sepecify the test script directory.... Set maindir = filesys.GetFolder("C:\temp") Set testCol = maindir.SubFolders ' Loop through each test in the collection For Each fl In testCol ' Verify the folder is a QTP test checkfolder = fl.Path & "\Action0" If (filesys.FolderExists(checkfolder)) Then ' The folder is a QTP test folder ' Convert test qtApp.Open fl.Path, False, False ' wscript.sleep 1000 ' Save converted test qtApp.Test.Save
End If Next qtApp.Quit ' Release the File System Objects Set testCol = Nothing Set maindir = Nothing Set filesys = Nothing ' Release the QuickTest Professional application object Set qtApp = Nothing Supposedly, this should do it if you run it on a machine with QTP 10 installed - though you would have to tweak it a bit for tests stored in QC. The idea is to open each test in edit mode, then save it.
Word Scripts MS Word Scripts 1) create a word document and write some data ==================== dim mw set mw=CreateObject("Word.Application") mw.Documents.Add mw.selection.typetext "hello" mw.ActiveDocument.SaveAs "e:\gcreddy.doc" mw.quit set mw=nothing 2) Create word, Create table and write all the services names ======================================== Set mw = CreateObject("Word.Application") mw.Visible = True Set dc = mw.Documents.Add() Set objRange = dc.Range() dc.Tables.Add objRange,1,3 Set objTable = dc.Tables(1) x=1 strComputer = "." Set wms=GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = wms.ExecQuery("Select * from Win32_Service") For Each s in colItems If x > 1 Then objTable.Rows.Add() End If objTable.Cell(x, 1).Range.Font.Bold = True objTable.Cell(x, 1).Range.Text = s.Name objTable.Cell(x, 2).Range.text = s.DisplayName objTable.Cell(x, 3).Range.text = s.State x=x+1 Next 3) script to display all the doc files in all the drives in the system ========================================= Dim mw Set mw=CreateObject("Word.Application")
Set fs=createobject("Scripting.FileSystemObject") Set d=fs.Drives mw.FileSearch.FileName="*.doc" For each dr in d msgbox dr mw.FileSearch.LookIn=dr mw.FileSearch.SearchSubFolders=True mw.FileSearch.Execute For each i in mw.FileSearch.FoundFiles print i Set f=fs.GetFile(i) print f.Name&" "&f.Size&" "&f.DateCreated print "-------------------------------------------------------------------" Next Next mw.Quit 4) Counting the number of times a word appears in a word document ========================================= Set objWord=CreateObject("Word.Application") Set myfile=objWord.Documents.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\xyz.doc") strText="gcreddy" strRead=myfile.Content Set RegExp=new regexp regexp.ignorecase=True regexp.global=True regexp.pattern=strText Set matches=regexp.execute(strRead) matchesFound=matches.count msgbox matchesfound myfile.close set objFso=Nothing
XML Scripts XML Scripts VBScript to read XML Set xmlDoc = CreateObject(Msxml2.DOMDocument) xmlDoc.load(D:\gcreddy.xml) Set ElemList = xmlDoc.getElementsByTagName(segment) filepath = ElemList.item(0).getAttribute(filePath) MsgBox filepath Set ElemList = xmlDoc.getElementsByTagName(description) plot = ElemList.item(0).Text MsgBox plot How Get Root Element attributes value from XML file Function GetRootElementAttributeValueFromXML(sFileNameWithPath,sAttribute) Why we need to ADD 2 because each attribute followed by (=) and () iLenOfValue=len(sAttribute) + 2 Set doc = XMLUtil.CreateXML() doc.LoadFile sFileNameWithPath Set root = doc.GetRootElement() IF instr(1,root,sAttribute) <= 0 then Reporter.ReportEvent micFail,sAttribute,Not Found in XML file. exitrun(0) Else
QTP Skills 7 Steps to Improve Skills in QTP I) QTP Testing Process In order to use QTP IDE properly, you should have good command on QTP Testing process. a) Planning a) Analyzing the AUT b) Implementing Automation Framework c) Creating/Selecting Test cases d) Collecting Test Data e) Automation Infrastrucure development f) Tool settings Configuration & Globalization b) Generating the basic Test 1) Keyword driven methodology/Shared object repository method/Preparing the script manually 2) Descriptive programming/Programmatic Descriptions i) Entering Programmatic Descriptions Directly into Statements ii) Using Description Objects for Programmatic Descriptions iii) Retrieving Child Objects iv) Using the Index Property in Programmatic Descriptions c) Enhancing the Test a) Adding Comments b) Creating Checkpoints Programmatically c) Synchronization d) Parameterization e) Inserting Programmatic statements f) Enhancing Tests with the windows API g) Calling Functions and/or Actions d) Debugging the Test e) Running the Test f) Analyzing the Test Results g) Reporting Defects a. Manual Defect Reporting b. Tool based Defect Reporting c. Integration with Quality Center II) VB Script VbScript is the QTP Tool Default Scripting Language for applaying Progamming Logic, so learn Vbscript indepth. Below fundamentals & Features are Important:
a) VBScript Fundamentals 1)Introduction a) Scripting Languages vs. Programming Languages b) Basic Features of VBScript c) Hosting Environments & Script Engines d) Crating & running a Script 2) Variables and Constants a) VBScript data types b) Declaring Variables and Option Explicit Statement c) Assigning Values to Variables d) Scalar Variables and Array Variables e) Dynamic Arrays, Dimensional Arrays f) Constants g) Variables Vs. Constants 3) VBScript Operators a) Operator Precedence b) Arithmetic Operators c) Comparison Operators d) Concatenation Operators e) Logical Operators 4) Flow Control (I. Conditional Statements) a) VBScript Conditional Statements b) Running a state if condition is true (Single line Syntax) c) Running a block of Statements if Condition is true d) Running Certain Statements if a Condition is True and Running Others if a Condition is False e) Deciding Among Several Alternatives (IF..Else If) f) Executing a certain block of statements when two / more conditions are True (Nested If...) g) Deciding Among Several Alternatives (Selct case Statement) 5) Flow Control (II. Looping through the code) a) Do...Loop (Loops while or until a condition is True.) b) While...Wend (Loops while a condition is True.) c) For...Next: Uses a counter to run statements a specified number of times. d) For Each...Next (Repeats a group of statements for each item in a collection or each element of an array.) e) Nested Loops 6) VBScript Procedures a) Sub Procedures b) Function Procedures c) Creating & Calling Procedures 7) Coding Conventions a) Constant Naming Conventions b) Variable Naming Conventions c) Variable Scope Prefixes d) Object Naming Conventions e) Code Commenting Conventions b) Advanced VBScript 1) VBScript Intrinsic (Pre-Defined) Functions a) Conversions b) Dates/Times c) Formatting Strings d) Input/Output e) Math f) Miscellaneous
g) Rounding h) Strings i) Variants 2) Regular Expressions a) Uses for Regular Expressions b) Regular Expression Syntax c) Build a Regular Expression d) Order of Precedence e) Ordinary Characters f) Character Matching g) Anchors h) Alternation and Grouping i) Backreferences j) Regular Expression (RegExp) Object 3) File System Operations a) Computer File System b) Working with Drives and Folders c) Working with Flat Files d) Working with Word Docs e) Working with Excel Sheets 4) Database Operations a) ActiveX Data Objects b) ADODB Connection Object & Recordset Object c) Test Database Creation & Collecting Test Data d) Databases Connections (Ms-Access, SQL Server and Oracle) e) Data Driven Testing by fetching Data from a Database f) Data Comparisons 5) Methods, Objects and Classes a) VBScript Global Methods b) QTP Methods c) FileSystemObject d) Dictionary Object e) Classes 6) Error Handling a) Error Handling Guidelines b) Error Handling in QuickTest Professional c) Error Preventing d) Synchronization e) QTP Exit Statements f) VBScript error handling vs. Recovery Scenarios g) On Error Statement h) Err Object III) Automation Framework Automation Framework is a Systamatic Approach for Automating, Software Testing Process. In order to Create & Run Tests as well oraganizing & Managing Automation Resources, a well defined Framework required. Framework may vary from one company to another. Below concepts are important to learn: o Test Automation Framework o Types of Framework
o Keyword Driven Framework o Framework Structure o Developing a Robust Automation Framework o Implementing & Managing Automation Resources IV) COM/DCOM Technologies When working with QTP, It is important to know, Microsoft Applications like: o MS Excel, o Ms Word, o Outlook Express and o Internet Explorer V) XML XML is an extremely popular and useful format. It can be used in several areas in QTP. Ex: o Exporting objects, o Environment Variables, o Data driven Testing o Data transporting etc. VI) SQL SQL Knowledge is highly recomendable in order to perform Database Testing using QTP Below concepts are important: o Database Fundamentals o Data Creation & Exporting o Database Connections o Select Statements VII) HTML, DOM In order to work with Web based Applications, It is important to femiliar with web technologies like: o HTML, DHTML o Flash o HTTP like Protocols o DOM (Documentation Object Model)
Error Handling in QTP Error Handling: Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors. Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions. Error Handling in QuickTest Professional: QTP and VBScript give the Test Engineer some tools to handle errors and Exceptions. Error Preventing: A good method for using error handling is to try to prevent them. When an error occurred, Report it in detail. When working with GUI objects, use the Window.Exist property. Every IfThen..End If statement has the Else part, the same for Select Case. Use Case Else.
Error Handling Methods in QTP and VB Script: a) Synchronization b) Exist Property c) Recover Scenarios d) On Error Statement Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops. Whenever possible, you use structured exception handling in your code, rather than resorting to unstructured exception handling and the On Error statement. Parts: GoToline Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur. GoTo 0 Disables enabled error handler in the current procedure and resets it to Nothing. GoTo -1 Disables enabled exception in the current procedure and resets it to Nothing. Resume Next Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects. on Error Resume Next Example1: Dim a a=1 b-2 MsgBox a + b ' displays result without showing error Example2: Function Sum(Num1, Num2) If IsNumeric(Num1) = False Or IsNumeric(Num2) = False Then On Error Resume Next Err.Raise vbObjectError + 100, "Sum Function", _ "One or more parameters are invalid." Exit Function End If Sum = Num1 +Num2 End Function Call Sum("gcreddy","QTP") 'Comes out without showing error Call Sum(100,200) ' returns sum of 100,200 as 300 e) Error Object The Err object is an intrinsic object with global scope there is no need to create an instance of it in your code.
The properties of the Err object are set by the generator of an error Visual Basic, an Automation object, or the VBScript programmer. The default property of the Err object is Number. Err.Number contains an integer and can be used by an Automation object to return an SCODE. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method. The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err. Example: On Error Resume Next Err.Raise 6 ' Raise an overflow error. MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description) Err.Clear ' Clear the error. Err Object Properties and Methods Properties Description Property HelpContext Property HelpFile Property Number Property Source Property Methods Clear Method Raise Method f) Exit Statement Open 30 to 40 Orders in Flight Reservation Window, if some records not available handle the situation Option Explicit Dim Order_Number If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "gcreddy" Dialog("Login").WinEdit("Password:").SetSecure "4c2e1e65bf29943393b6940f116d35231ce5fb7e" Dialog("Login").WinButton("OK").Click End If For Order_Number= 30 to 40 step 1 Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist(3) Then Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click Reporter.ReportEvent micWarning,"Res", "Up to "& Order_Number-1 &" Order only available" Exit For End If Next
Environment Variables Environment Variables in QTP These are global variables; if you want to use some variables globally (From number of tests) declaring as global variables is better. If we declare as local variables in number of tests, modifications are difficult. Types of Environment variables: 1. Built in variables: These are system defined variables, we can access from all tests but these are designed as read only. 2. User defined variables: Variables that we predefine in the active external environment variables file. We can create as many files as we want and we can change values of variables. Usage of environment variables: Syntax: Variable = Environment(environment variable name) Ex: X=Environment (ActionName) Msgbox x Example Script: ProductDir =environment ("ProductDir") app= "\samples\flight\app\flight4a.exe" Systemutil.Run ProductDir & app Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "kajal" Dialog("Login").WinEdit("Password:").SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407" Dialog("Login").WinButton("OK").Click Creating user defined environment variables: Navigation: File > settings > Environment > select variable type as user defined > click add icon (+) > enter variable name & Value > click ok (like this we can create number of variables) > click export > browse path & enter file name, save with xml extension > click ok. Associating environment variable file: Navigation: File > settings >Environment > select variable type as user defined > check load variables and values from the external file > browse path of the xml file > click apply & ok. Or We can load environment file directly
Environment.loadfromfilepath of the xml file Usage of user defined Environment variables: Associate environment file to current test: Variable = Environment (Variable Name) X=environment (city) Msgbox x Modifying Environment files: Select XML file>open with notepad>modify the values>Save.
Virtual Object Configuration Virtual Object Configuration Virtual Object Configuration: Virtual Object Configuration is a process of making the QTP to treat a specified area or a user defined object as Virtual Object. Virtual objects enable us to create and run tests on objects that are not normally recognized by QTP. We can manage the virtual objects defined on our computer using the Virtual Object Manager. Navigation: Select Tools Menu Go to Virtual objects Select New Virtual Object option Click Next Mark the area in the Application with help of mark object button Click next Select one of the following options o o Entire Parent hierarchy Parent only Click on Next Specify the Desired object name Specify the Desired collection name Click finish Virtual Object Manager: Virtual object Manager feature enable us to create and manage Virtual Objects
Executing a group of Tests or series of tests at a time is known as Batch Testing or Batch Execution. For performing Batch Testing, QTP is providing a separate Tool called Test Batch Runner. Steps for Batch Testing: 1). Create Individual Tests and Run once. 2). Open 'Test batch Runner' Tool and Form Batches. 3) Provide permission to 'Test batch Runner' to run tests 4). Run or Execute Test Batches from Test Batch Runner. 5) View Test wise Result in 'Test Result Viewer'. Note: QTP doesnt provide Batch wise result. Forming a Test Batch: Launch Test Batch Runner. Navigation: Start>program>quicktest professional>Tools>Test Batch Runner>File>new>batch>add>browse path of the test (like this add number of tests)>save with MTB extension (Module test batche)>close test batch runner. Running or Executing a Test Batch Open Test Batch Runner Tool Navigation: File>open>browse path of the test batch>batch>run Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one. Note: Allowing other products to Run Tests. Navigation: Tools>Options>Run>check allow other mercury products>apply & Ok Executing partial Test Batch Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch.
Recovery Scenarios Recovery Scenario Manager To recover from unexpected events and errors that are occurred in the test environment during run session, we can use Recovery Scenario Manager. For good recovery, error must be known the occurrence is unknown. There are (4) Types of events such as: (i) Application Crash An open application fails during Test Run. Navigation: Resources Menu -> Recovery Scenario Manager-> Click New-> Click Next -> Select Application Crash as Trigger event->Next ->Select selected executable
application->Next ->Select Recovery Operation [Keyboard, Mouse Operation, Close Application Process, function Call, Restart, Microsoft Windows] ->Next ->If you want to check Add another operation else uncheck->Next ->Next ->Enter Scenario Name ->Next->Select Option ->Finish ->Close ->Save the scenario in specified location with .qrs (qrs stands for QuickTest Recovery Scenario.) (ii) Popup Window. To handle unwanted popups. Navigation: Resources Menu ->Recovery Scenario Manager ->New ->Next ->Select Popup Window as Trigger event ->Next ->Click on Hand Icon ->Show unwanted window with Hand icon ->Next ->Next ->Select function call as Recovery Operation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browse the .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] ->Next ->Enter Scenario Name ->Next ->Select Option -> Finish ->Save the scenario with .qrs ->Record required Recovery Operation [Click ok, Click Cancel] take the script into function ->Save the library file ->Click Run (iii) Test Run Error. A step in your test does not run successfully then Test Run Error can be raised. Navigation : Resources Menu ->Recovery Scenario Manager ->New ->Next ->Select Testrunerror Window as Trigger event ->Next ->select any error o ->Next ->Next ->Select function call as Recovery Operation ->Next [Open Notepad ->Save empty file with .vbs extension] ->Browse the .vbs fie path ->Next ->Uncheck Add another Recovery Operation ->Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] Next Enter Scenario Name Next Select Option Finish Save the scenario with .qrs Record required Recovery Operation [Click ok, Click Cancel] take the script into function Save the library file Click Run (iv) Object State. The property values of an object in your application match specified values. You can specify property values for each object in the hierarchy. Navigation: Resources Menu -> Recovery Scenario Manager -> New -> Next -> Select Object state Window as Trigger event -> Next -> Click on Hand Icon -> Show object with hand icon -> Next -> Next->select object property with value (enabled ,false)->click next -> Select function call as Recovery Operation -> Next [Open Notepad -> Save empty file with .vbs extension] -> Browse the .vbs fie path -> Next -> Uncheck Add another Recovery Operation -> Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] -> Next-> Enter Scenario Name -> Next -> Select Option -> Finish -> Save the scenario with .qrs -> Record required Recovery Operation [Click ok, Click Cancel] take the script into function -> Save the library file -> Click Run
Automation Object Model AOM Scripting (Automation Object Model) Object Model: An object model is a structural representation of software objects (classes) that comprise the implementation of a system or application. An object model defines a set of classes and interfaces, together with their properties, methods and events, and their relationships.
We can use QTP Automation object Model to write scripts, that automate our QTP operations. QTP Automation object model provides objects, methods and properties that enable us to control QTP from another application. We can use Scripting languages or programming languages such as VBscript, Java script or VC++, .Net for automating QTP operations. Example: 1) Write an AOM Script to launch QTP Tool, Execute Tests and to close the QTP Tool option explicit Dim qtApp Set qtApp=createobject ("Quicktest.Application") qtApp.Launch qtApp.visible=True qtApp.open "C:\Documents and Settings\admin\My Documents\login" qtApp.Test.Run qtApp.Test.Close qtApp.open "C:\Documents and Settings\admin\My Documents\open order" qtApp.Test.Run qtApp.Test.Close qtApp.quit Set qtApp=Nothing Note: AOM Script can be used in Automation framework as an Initialization script. '-----------------------------------------------------------------2) Write an AOM script to execute series of tests Dim objFso,objQtp,myFile,i,gcreddy Set objQtp = CreateObject("Quicktest.Application") objQtp.Visible = True objQtp.Launch Set objFso =CreateObject("Scripting.FileSystemObject") Set myFile = objFso.OpenTextFile("C:\Users\Chinni\Desktop\Test\gcreddy.txt") i =1 Do Until myFile.AtEndOfStream =True testurl = myFile.ReadLine objQtp.Open gcreddy objQtp.Test.Run objQtp.Test.Close i = i+1 Loop objQtp.Quit Set objQtp = Nothing
Dynamic Handling of Object Repositories Dynamic handling of object Repositories Loading repositories during running, finding path of the repositories and removing repositories is called Dynamic Handling of Object Repositories. Using this feature we can increase QTP performance. To do this, QTP is providing an object called RepositoriesCollection. Syntax for Loading a Repository: RepositoriesCollection.Add Path of the Repository File Syntax for finding Position of the Repository: Variable=RepositoriesCollection.Find(Path of the Repository) Syntax for Removing the Repository: RepositoriesCollection.Remove(position) Syntax for Removing All Repositories: RepositoriesCollection.RemoveAll Example: RepPath="C:\Documents and Settings\Administrator\My Documents\Login.tsr" RepositoriesCollection.Add (RepPath) systemutil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "sudhakar" Dialog("Login").WinEdit("Password:").Set "mercury" Dialog("Login").WinButton("OK").Click pos=RepositoriesCollection.Find(RepPath) RepositoriesCollection.Remove(pos) RepositoriesCollection.RemoveAll *********************************** Go to home page for QTP Guide, Script examples, Interview questions and Framework etc.
Automation Framework Hybrid Framework Hybrid Framework: It is a mixture of two or more approaches -------To explain this Hybrid Framework, I have taken QTP sample Application (Flight Reservations) -----------Process Guidelines: ------------------i) Creating the Folder structure ii) Creating Automation Resources Iii) Create Organizer spread sheet Organizer provides instructions to the Driver iv) Generating the driver Script (QTP Test)
(We associate all resources to the Driver Driver executes tests based on Organizer spread sheet instructions) v) Generate the initialization Script (AOM Script file) It launches the QTP Tool, Calls the Driver Script Driver executes tests one by one It closes the QTP Tool -----------------------Test Scenarios: Click on this Excel sheet Image in order to get Big size and Clear Image
Hybrid Framework Functions: '*********************************************** ' Login Operation '*********************************************** Function Login(Agent, Password) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Password Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(12) Then 'Window("Flight Reservation").Close Login="Login Operation Sucessful" 'Msgbox Login Else Systemutil.CloseDescendentProcesses Login="Login Failed" 'Msgbox Login End if End Function '*********************************************** ' Open Order '*********************************************** Function Open_Order(ord) Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("OpenOrder").Click Window("Flight Reservation").Dialog("Open Order").Activate Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("OrderNum").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("text:=OK").Click OrderNum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty("text") OrderNum=Cint(OrderNum) If ord=OrderNum Then Open_Order=ord&" Order Opened Sucessfully" 'Msgbox Order_Number
Else Open_Order=ord&" Order Not Opened" 'Msgbox Order_Number End If End Function '*********************************************** ' Update Order '*********************************************** Function Update_Order(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("OpenOrder").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("OrderNum").Set "5" Window("Flight Reservation").Dialog("Open Order").WinButton("text:=OK").Click Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click Wait 10 Message=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty("text") If Message="Update Done..." Then Update_Order="Order Updated Sucessfully" 'Msgbox Update_Order Else Update_Order="Order Not Updated" 'Msgbox Update_Order End If End Function '*********************************************** ' Close Application '*********************************************** Function Close_App() If Window("Flight Reservation").Exist(3) Then Window("Flight Reservation").Close End If End Function '*********************************************** ' Login for Data Driven Testing '*********************************************** Function Login2(Agent, Password) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Password Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(12) Then Window("Flight Reservation").Close Login2="Login Operation Sucessful" 'Msgbox Login Else Systemutil.CloseDescendentProcesses Login2="Login Failed" 'Msgbox Login End if End Function '*********************************************** ' Open Order for Data Driven Testing '*********************************************** Function Open_Order2(ord) Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("OpenOrder").Click Window("Flight Reservation").Dialog("Open Order").Activate Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("OrderNum").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("text:=OK").Click OrderNum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty("text") OrderNum=Cint(OrderNum) If ord=OrderNum Then Open_Order2=ord&" Order Opened Sucessfully" 'Msgbox Order_Number Else Open_Order2=ord&" Order Not Opened" 'Msgbox Order_Number End If End Function '*********************************************** ' Update Order for Data Driven Testing '*********************************************** Function Update_Order2(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("OpenOrder").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("OrderNum").Set "5" Window("Flight Reservation").Dialog("Open Order").WinButton("text:=OK").Click Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click Wait 10 Message=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty("text") If Message="Update Done..." Then Update_Order2="Order Updated Sucessfully" 'Msgbox Update_Order Else Update_Order2="Order Not Updated" 'Msgbox Update_Order End If End Function Organizer Spread Sheet: I st Sheet "Module" Click on this Excel sheet Image in order to get Big size and Clear Image
II nd Sheet "TestCase" Click on this Excel sheet Image in order to get Big size and Clear Image
III rd Sheet "TestStep" Click on this Excel sheet Image in order to get Big size and Clear Image
Test Data: Click on this Excel sheet Image in order to get Big size and Clear Image
Driver Script: 'Adding sheets to Run-time data table DataTable.AddSheet "Module" DataTable.AddSheet "TestCase" DataTable.AddSheet "TestStep" DataTable.AddSheet "Login" 'Importing data from External File DataTable.ImportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\Orginizer\Organizer.xls",1,3 DataTable.ImportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\Orginizer\Organizer.xls",2,4 DataTable.ImportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\Orginizer\Organizer.xls",3,5 DataTable.ImportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\TestData\data.xls",1,6 'Capturing Executable Modules from Module Sheet MRowCount=DataTable.GetSheet("Module").GetRowCount For i=1 to MRowCount Step 1 DataTable.SetCurrentRow(i) ModuleExe=DataTable(3,"Module") If UCase(ModuleExe)="Y" Then ModuleId=DataTable(1,"Module") 'Msgbox "ModuleId: " & ModuleId ' Capturing executable test cases under executable modules TCRowCount=DataTable.GetSheet("TestCase").GetRowCount For j=1 to TCRowCount Step 1 DataTable.SetCurrentRow(j) TCCaseExe=DataTable(3,"TestCase") ModuleId2=DataTable(4,"TestCase") If UCase(TCCaseExe)="Y" and ModuleId=ModuleId2 Then TestCaseId=DataTable(1,"TestCase") 'Msgbox TestCaseId 'Capturing keywords for executable steps TSRowCount=DataTable.GetSheet("TestStep").GetRowCount For k=1 to TSRowCount Step 1 DataTable.SetCurrentRow(k) TestCaseId2 = DataTable(5,"TestStep") If TestCaseId=TestCaseId2 Then keyword=DataTable(4,"TestStep") 'msgbox keyword Select Case keyword Case "ln" Result=Login("abcd","mercury")
DataTable(7,"TestStep")=Result Case "oo" Result=Open_Order(5) DataTable(7,"TestStep")=Result Case "uo" Result=Update_Order(5) DataTable(7,"TestStep")=Result Case "ca" Close_App() Case "lnd" Rows=DataTable.GetSheet("Login").GetRowCount For m=1 to Rows Step 1 DataTable.SetCurrentRow(m) Result=Login2(DataTable(1,"Login"),DataTable(2,"Login")) DataTable(3,"Login")=Result Next Case "ood" Rows=DataTable.GetSheet("Login").GetRowCount For n=1 to Rows Step 1 DataTable.SetCurrentRow(n) Result=Open_Order2(DataTable(4,"Login")) DataTable(5,"Login")=Result Next Case "uod" Rows=DataTable.GetSheet("Login").GetRowCount For p=1 to Rows Step 1 DataTable.SetCurrentRow(p) Result=Update_Order2(DataTable(6,"Login")) DataTable(7,"Login")=Result Next End Select End If Next End If Next End If Next DataTable.ExportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\TestResult\Result1.xls","TestStep" DataTable.ExportSheet "C:\Documents and Settings\gcr\Desktop\Proj_Automation\TestResult\Result1.xls","Login" Initialization Script: Dim objQTP Set objQTP=CreateObject("QuickTest.Application") objQTP.Visible=True objQTP.Launch objQTP.Open "C:\Documents and Settings\gcr\Desktop\Proj_Automation\Drivers\Driver1" objQTP.Test.Run objQTP.Test.Close objQTP.Quit Set objQTP=Nothing
Web Testing
Web Applications Testing Introduction The instant worldwide audience of any Web Browser Enabled Application -- a Website -- makes its quality and reliability crucial factors in its success. Correspondingly, the nature of Websites and Web Applications pose unique software testing challenges. Webmasters, Web applications developers, and Website quality assurance managers need tools and methods that meet their specific needs. Mechanized testing via special purpose Web testing software offers the potential to meet these challenges. Our technical approach, based on existing Web browsers, offers a clear solution to most of the technical needs for assuring Website quality.
Websites impose some entirely new challenges in the world of software quality! Within minutes of going live, a Web application can have many thousands more users than a conventional, non-Web application. The immediacy of the Web creates immediate expectations of quality and rapid application delivery, but the technical complexities of a Website and variances in the browser make testing and quality control that much more difficult, and in some ways, more subtle, than "conventional" client/server or application testing. Automated testing of Websites is an opportunity and a challenge. Dimensions of Quality There are many dimensions of quality; each measure will pertain to a particular Website in varying degrees. Here are some common measures:
y y y y y y
Timeliness: Websites change often and rapidly. How much has a WebSite changed since the last upgrade? How do you highlight the parts that have changed? Structural Quality: How well do all of the parts of the WebSite hold together? Are all links inside and outside the WebSite working? Do all of the images work? Are there parts of the WebSite that are not connected? Content: Does the content of critical pages match what is supposed to be there? Do key phrases exist continually in highly-changeable pages? Do critical pages maintain quality content from version to version? What about dynamically generated HTML (DHTML) pages? Accuracy and Consistency: Are today's copies of the pages downloaded the same as yesterday's? Close enough? Is the data presented to the user accurate enough? How do you know? Response Time and Latency: Does the WebSite server respond to a browser request within certain performance parameters? In an e-commerce context, how is the end-to-end response time after a SUBMIT? Are there parts of a site that are so slow the user discontinues working? Performance: Is the Browser --> Web --> ebSite --> Web --> Browser connection quick enough? How does the performance vary by time of day, by load and usage? Is performance adequate for e-commerce applications? Taking 10 minutes -- or maybe even only 1 minute -- to respond to an e-commerce purchase may be unacceptable!
Impact of Quality Quality remains is in the mind of the WebSite user. A poor quality WebSite, one with many broken pages and faulty images, with Cgi-Bin error messages, etc., may cost a lot in poor customer relations, lost corporate image, and even in lost sales revenue. Very complex, disorganized WebSites can sometimes overload the user.
The combination of WebSite complexity and low quality is potentially lethal to Company goals. Unhappy users will quickly depart for a different site; and, they probably won't leave with a good impression. Browser: The browser is the viewer of a WebSite and there are so many different browsers and browser options that a well-done WebSite is probably designed to look good on as many browsers as possible. This imposes a kind of de facto standard: the WebSite must use only those constructs that work with the majority of browsers. But this still leaves room for a lot of creativity, and a range of technical difficulties. And, multiple browsers' renderings and responses to a WebSite have to be checked. Display Technologies: What you see in your browser is actually composed from many sources:
y y y
HTML. There are various versions of HTML supported, and the WebSite ought to be built in a version of HTML that is compatible. This should be checkable. Java, JavaScript, ActiveX. Obviously JavaScript and Java applets will be part of any serious WebSite, so the quality process must be able to support these. On the Windows side, ActiveX controls have to be handled well. Cgi-Bin Scripts. This is link from a user action of some kind (typically, from a FORM passage or otherwise directly from the HTML, and possibly also from within a Java applet). All of the different types of Cgi-Bin Scripts (perl, awk, shell-scripts, etc.) need to be handled, and tests need to check "end to end" operation. This kind of a "loop" check is crucial for e-commerce situations. Database Access. In e-commerce applications you are either building data up or retrieving data from a database. How does that interaction perform in real world use? If you give in "correct" or "specified" input does the result produce what you expect? Some access to information from the database may be appropriate, depending on the application, but this is typically found by other means. Navigation: Users move to and from pages, click on links, click on images (thumbnails), etc. Navigation in a WebSite is often complex and has to be quick and error free. Object Mode: The display you see changes dynamically; the only constants are the "objects" that make up the display. These aren't real objects in the OO sense; but they have to be treated that way. So, the quality test tools have to be able to handle URL links, forms, tables, anchors, buttons of all types in an "object like" manner so that validations are independent of representation. Server Response: How fast the WebSite host responds influences whether a user (i.e. someone on the browser) moves on or gives up. Obviously, InterNet loading affects this too, but this factor is often outside the Webmaster's control at least in terms of how the WebSite is written. Instead, it seems to be more an issue of server hardware capacity and throughput. Yet, if a WebSite becomes very popular -- this can happen overnight! -- loading and tuning are real issues that often are imposed -- perhaps not fairly -- on the WebMaster. Interaction & Feedback: For passive, content-only sites the only real quality issue is availability. For a WebSite that interacts with the user, the big factor is how fast and how reliable that interaction is. Concurrent Users: Do multiple users interact on a WebSite? Can they get in each others' way? While WebSites often resemble client/server structures, with multiple users at multiple locations a WebSite can be much different, and much more complex, than complex applications.
Functionality Testing: Test for - all the links in web pages, database connection, forms used in the web pages for submitting or getting information from user, Cookie testing. Check all the links:
y y y y y y
Test the outgoing links from all the pages from specific domain under test. Test all internal links. Test links jumping on the same pages. Test links used to send the email to admin or other users from web pages. Test to check if there are any orphan pages. Lastly in link checking, check for broken links in all above-mentioned links.
Test forms in all pages: Forms are the integral part of any web site. Forms are used to get information from users and to keep interaction with them. So what should be checked on these forms?
y y y y
First check all the validations on each field. Check for the default values of fields. Wrong inputs to the fields in the forms. Options to create forms if any, form delete, view or modify the forms.
Cookies testing: Cookies are small files stored on user machine. These are basically used to maintain the session mainly login sessions. Test the application by enabling or disabling the cookies in your browser options. Test if the cookies are encrypted before writing to user machine. If you are testing the session cookies (i.e. cookies expire after the sessions ends) check for login sessions and user stats after session end. Check effect on application security by deleting the cookies. Validate your HTML/CSS: If you are optimizing your site for Search engines then HTML/CSS validation is very important. Mainly validate the site for HTML syntax errors. Check if site is crawl able to different search engines. Database testing: Data consistency is very important in web application. Check for data integrity and errors while you edit, delete, modify the forms or do any DB related functionality. Check if all the database queries are executing correctly, data is retrieved correctly and also updated correctly. More on database testing could be load on DB, we will address this in web load or performance testing below. Usability Testing: Test for navigation: Navigation means how the user surfs the web pages, different controls like buttons, boxes or how user using the links on the pages to surf different pages. Usability testing includes: Web site should be easy to use. Instructions should be provided clearly. Check if the provided instructions are correct means whether they satisfy purpose. Main menu should be provided on each page. It should be consistent. Content checking: Content should be logical and easy to understand. Check for spelling errors. Use of dark colors annoys users and should not be used in site theme. You can follow some standards that are used for web page and content building. These are common accepted standards like as I mentioned above about annoying colors, fonts, frames etc. Content should be meaningful. All the anchor text links should be working properly. Images should be placed properly with proper sizes. These are some basic standards that should be followed in web development. Your task is to validate all for UI testing Other user information for user help: Like search option, sitemap, help files etc. Sitemap should be present with all the links in web sites with proper tree view of navigation. Check for all links on the sitemap.
Search in the site option will help users to find content pages they are looking for easily and quickly. These are all optional items and if present should be validated. Interface Testing: The main interfaces are: Web server and application server interface Application server and Database server interface. Check if all the interactions between these servers are executed properly. Errors are handled properly. If database or web server returns any error message for any query by application server then application server should catch and display these error messages appropriately to users. Check what happens if user interrupts any transaction in-between? Check what happens if connection to web server is reset in between? Compatibility Testing: Compatibility of your web site is very important testing aspect. See which compatibility test to be executed:
y y y y
Browser compatibility: In my web-testing career I have experienced this as most influencing part on web site testing. Some applications are very dependent on browsers. Different browsers have different configurations and settings that your web page should be compatible with. Your web site coding should be cross browser platform compatible. If you are using java scripts or AJAX calls for UI functionality, performing security checks or validations then give more stress on browser compatibility testing of your web application. Test web application on different browsers like Internet explorer, Firefox, Netscape navigator, AOL, Safari, Opera browsers with different versions. OS compatibility: Some functionality in your web application is may not be compatible with all operating systems. All new technologies used in web development like graphics designs, interface calls like different APIs may not be available in all Operating Systems. Test your web application on different operating systems like Windows, Unix, MAC, Linux, Solaris with different OS flavors. Mobile browsing: This is new technology age. So in future Mobile browsing will rock. Test your web pages on mobile browsers. Compatibility issues may be there on mobile. Printing options: If you are giving page-printing options then make sure fonts, page alignment, page graphics getting printed properly. Pages should be fit to paper size or as per the size mentioned in printing option. Performance testing: Web application should sustain to heavy load. Web performance testing should include:
Web Load Testing Web Stress Testing Test application performance on different internet connection speed. In web load testing test if many users are accessing or requesting the same page. Can system sustain in peak load times? Site should handle many simultaneous user requests, large input data from users, Simultaneous connection to DB, heavy load on specific pages etc.
Stress testing: Generally stress means stretching the system beyond its specification limits. Web stress testing is performed to break the site by giving stress and checked how system reacts to stress and how system recovers from crashes. Stress is generally given on input fields, login and sign up areas. In web performance testing web site functionality on different operating systems, different hardware platforms is checked for software, hardware memory leakage errors, Security Testing: Following are some tests for web security testing:
y y
y y y y y
Test by pasting internal URL directly into browser address bar without login. Internal pages should not open. If you are logged in using username and password and browsing internal pages then try changing URL options directly. I.e. If you are checking some publisher site statistics with publisher site ID= 123. Try directly changing the URL site ID parameter to different site ID which is not related to log in user. Access should deny for this user to view others stats. Try some invalid inputs in input fields like login username, password and input text boxes. Check the system reaction on all invalid inputs. Web directories or files should not be accessible directly unless given download option. Test the CAPTCHA for automates scripts logins. Test if SSL is used for security measures. If used proper message should get displayed when user switch from nonsecure http:// pages to secure https:// pages and vice versa. All transactions, error messages, security breach attempts should get logged in log files somewhere on web server.
IEEE Test Incident Report 1.1 Purpose To document any event that occurs during the testing process that requires investigation. 1.2 Outline A test incident report shall have the following structure: a) Test incident report identifier; b) Summary; c) Incident description; d) Impact.
The sections shall be ordered in the specified sequence. Additional sections may be included at the end. If some or all of the content of a section is in another document, then a reference to that material may be listed in place of the corresponding content. The referenced material must be attached to the test incident report or available to users of the incident report. Details on the content of each section are contained in the following subclauses. 1.2.1 Test incident report identifier Specify the unique identifier assigned to this test incident report. 1.2.2 Summary Summarize the incident. Identify the test items involved indicating their version/revision level. References to the appropriate test procedure specification, test case specification, and test log should be supplied. 1.2.3 Incident description Provide a description of the incident. This description should include the following items: a) Inputs; b) Expected results; c) Actual results; d) Anomalies; e) Date and time; f) Procedure step; g) Environment; h) Attempts to repeat; i) Testers; j) Observers.
Related activities and observations that may help to isolate and correct the cause of the incident should be included (e.g., describe any test case executions that might have a bearing on this particular incident and any variations from the published test procedure). 1.2.4 Impact If known, indicate what impact this incident will have on test plans, test design specifications, test procedure specifications, or test case specifications.
Introduction to Descriptive Programming. How to write Descriptive Programming? When and Where to use Descriptive programming? Some points to note with Descriptive Programming. Introduction to Descriptive Programming: Descriptive programming is used when we want to perform an operation on an object that is not present in the object repository. There can be various valid reason to do so. We will discuss them later in this article. How to write Descriptive Programming?
There are two ways in which descriptive programming can be used 1. By giving the description in form of the string arguments. 2. By creating properties collection object for the description. 1. By giving the description in form of the string arguments. This is a more commonly used method for Descriptive Programming. You can describe an object directly in a statement by specifying property:=value pairs describing the object instead of specifying an objects name. The general syntax is: TestObject("PropertyName1:=PropertyValue1", "..." , "PropertyNameX:=PropertyValueX") TestObjectthe test object class could be WebEdit, WebRadioGroup etc. PropertyName:=PropertyValuethe test object property and its value. Each property:=value pair should be separated by commas and quotation marks. Note that you can enter a variable name as the property value if you want to find an object based on property values you retrieve during a run session.
Consider the HTML Code given below: <--!input type="textbox" name="txt_Name"--> <--!input type="radio" name="txt_Name"--> Now to refer to the textbox the statement would be as given below Browser(Browser).Page(Page).WebEdit(Name:=txt_Name,html tag:=INPUT).set Test And to refer to the radio button the statement would be as given below Browser(Browser).Page(Page).WebRadioGroup(Name:=txt_Name,html tag:=INPUT).set Test If we refer to them as a web element then we will have to distinguish between the 2 using the index property Browser(Browser).Page(Page).WebElement(Name:=txt_Name,html tag:=INPUT,Index:=0).set Test Refers to the textbox Browser(Browser).Page(Page).WebElement(Name:=txt_Name,html tag:=INPUT,Index:=1).set Test Refers to the radio button To determine which property and value pairs to use, you can use the Object Spy: 1. Go to Tools -> Object Spy. 2. Select the "Test Object Properties" radio button. 3. Spy on the desired object. 4. In the Properties list, find and write down the properties and values that can be used to identify the object. 2. By creating properties collection object for the description. Properties collection also does the same thing as string arguments. The only difference is that it "collects" all the properties of a particular object in an instance of that object. Now that object can be referenced easily by using the instance, instead of writing "string arguments" again and again. It is my observation that people find "string arguments" [1] method much easier and intuitive to work with. To use this method you need first to create an empty description Dim obj_Desc Not necessary to declare Set obj_Desc = Description.Create Now we have a blank description in obj_Desc. Each description has 3 properties Name, Value and Regular Expression. obj_Desc(html tag).value= INPUT When you use a property name for the first time the property is added to the collection and when you use it again the property is modified. By default each property that is defined is a regular expression. Suppose if we have the following description obj_Desc(html tag).value= INPUT obj_Desc(name).value= txt.* This would mean an object with html tag as INPUT and name starting with txt. Now actually that .* was considered as regular expression. So, if you want the property name not to be recognized as a regular expression then you need to set the regularexpression property as FALSE obj_Desc(html tag).value= INPUT obj_Desc(name).value= txt.* obj_Desc(name).regularexpression= txt.* This is how we create a description. Now below is the way we can use it Browser(Browser).Page(Page).WebEdit(obj_Desc).set Test When we say .WebEdit(obj_Desc) we define one more property for our description that was not earlier defined that is its a text
box (because QTPs WebEdit boxes map to text boxes in a web page). If we know that we have more than 1 element with same description on the page then we must define index property for the that description Consider the HTML code given below <--!input type="textbox" name="txt_Name"--> <--!input type="textbox" name="txt_Name"--> Now the html code has two objects with same description. So distinguish between these 2 objects we will use the index property. Here is the description for both the object For 1st textbox: obj_Desc(html tag).value= INPUT obj_Desc(name).value= txt_Name obj_Desc(index).value= 0 For 2nd textbox: obj_Desc(html tag).value= INPUT obj_Desc(name).value= txt_Name obj_Desc(index).value= 1 Consider the HTML Code given below: <--!input type="textbox" name="txt_Name"--> <--!input type="radio" name="txt_Name"--> We can use the same description for both the objects and still distinguish between both of them obj_Desc(html tag).value= INPUT obj_Desc(name).value= txt_Name When I want to refer to the textbox then I will use the inside a WebEdit object and to refer to the radio button I will use the description object with the WebRadioGroup object. Browser(Browser).Page(Page).WebEdit(obj_Desc).set Test Refers to the text box Browser(Browser).Page(Page).WebRadioGroup(obj_Desc).set Test Refers to the radio button But if we use WebElement object for the description then we must define the index property because for a webelement the current description would return two objects. Getting Child Object: We can use description object to get all the objects on the page that matches that specific description. Suppose we have to check all the checkboxes present on a web page. So we will first create an object description for a checkboxe and then get all the checkboxes from the page Dim obj_ChkDesc Set obj_ChkDesc=Description.Create obj_ChkDesc(html tag).value = INPUT obj_ChkDesc(type).value = checkbox Dim allCheckboxes, singleCheckBox Set allCheckboxes = Browse(Browser).Page(Page).ChildObjects(obj_ChkDesc) For each singleCheckBox in allCheckboxes singleCheckBox.Set ON Next
The above code will check all the check boxes present on the page. To get all the child objects we need to specify an object description. If you wish to use string arguments [1], same thing can be accomplished by simple scripting. Code for that would be: i=0 Do While Browse(Browser).Page(Page).WebCheckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Exist Browse(Browser).Page(Page).WebCheckBox("html tag:=INPUT",type:=checkbox, "index:="&i).Set "ON" i=i+1 Loop Possible Operation on Description Objects Consider the below code for all the solutions Dim obj_ChkDesc Set obj_ChkDesc=Description.Create obj_ChkDesc(html tag).value = INPUT obj_ChkDesc(type).value = checkbox Q: How to get the no. of description defined in a collection A: obj_ChkDesc.Count Will return 2 in our case Q: How to remove a description from the collection A: obj_ChkDesc.remove html tag would delete the html tag property from the collection Q: How do I check if property exists or not in the collection? A: The answer is that its not possible. Because whenever we try to access a property which is not defined its automatically added to the collection. The only way to determine is to check its value that is use a if statement if obj_ChkDesc(html tag).value = empty then. Q: How to browse through all the properties of a properties collection? A: Two ways 1st: For each desc in obj_ChkDesc Name=desc.Name Value=desc.Value RE = desc.regularexpression Next 2nd: For i=0 to obj_ChkDesc.count - 1 Name= obj_ChkDesc(i).Name Value= obj_ChkDesc(i).Value RE = obj_ChkDesc(i).regularexpression Next Hierarchy of test description: When using programmatic descriptions from a specific point within a test object hierarchy, you must continue to use programmatic descriptions from that point onward within the same statement. If you specify a test object by its object repository name after other objects in the hierarchy have been described using programmatic descriptions, QuickTest cannot identify the object. For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), since it uses programmatic descriptions throughout the entire test object hierarchy. You can also use Browser("Index").Page(Desc1).Link(desc3), since it uses programmatic descriptions from a certain point in the description (starting from the Page object description).
However, you cannot use Browser(Desc1).Page(Desc1).Link("Example1"), since it uses programmatic descriptions for the Browser and Page objects but then attempts to use an object repository name for the Link test object (QuickTest tries to locate the Link object based on its name, but cannot locate it in the repository because the parent objects were specified using programmatic descriptions).
When and Where to use Descriptive programming? Below are some of the situations when Descriptive Programming can be considered useful: 1. One place where DP can be of significant importance is when you are creating functions in an external file. You can use these function in various actions directly , eliminating the need of adding object(s) in object repository for each action[If you are using per action object repository] 2. The objects in the application are dynamic in nature and need special handling to identify the object. The best example would be of clicking a link which changes according to the user of the application, Ex. Logout <>. 3. When object repository is getting huge due to the no. of objects being added. If the size of Object repository increases too much then it decreases the performance of QTP while recognizing a object. [For QTP8.2 and below Mercury recommends that OR size should not be greater than 1.5MB] 4. When you dont want to use object repository at all. Well the first question would be why not Object repository? Consider the following scenario which would help understand why not Object repository Scenario 1: Suppose we have a web application that has not been developed yet.Now QTP for recording the script and adding the objects to repository needs the application to be up, that would mean waiting for the application to be deployed before we can start of with making QTP scripts. But if we know the descriptions of the objects that will be created then we can still start off with the script writing for testing Scenario 2: Suppose an application has 3 navigation buttons on each and every page. Let the buttons be Cancel, Back and Next. Now recording action on these buttons would add 3 objects per page in the repository. For a 10 page flow this would mean 30 objects which could have been represented just by using 3 objects. So instead of adding these 30 objects to the repository we can just write 3 descriptions for the object and use it on any page. 5. Modification to a test case is needed but the Object repository for the same is Read only or in shared mode i.e. changes may affect other scripts as well. 6. When you want to take action on similar type of object i.e. suppose we have 20 textboxes on the page and there names are in the form txt_1, txt_2, txt_3 and so on. Now adding all 20 the Object repository would not be a good programming approach.