Top Banner

of 117

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

VB Script Variables

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

b) Cannot contain an embedded period. Dim abc 'Right

Dim ab.c 'worng Dim ab-c 'wrong

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

Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90 End Function Call res

Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: A = 200 City = Hyderabad X=100: Y=200 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) Although the number shown in the parentheses is 3, all arrays in VBScript are 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) = 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=xy Msgbox z 'True x=10 y=20

z=x0 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) 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

Batch Testing Batch Testing or Batch Execution

Executing a group of Tests or series of tests at a time is known as Batch Testing or Batch Execution. For performing Batch Testing, QTP is providing a separate Tool called Test Batch Runner. Steps for Batch Testing: 1). Create Individual Tests and Run once. 2). Open 'Test batch Runner' Tool and Form Batches. 3) Provide permission to 'Test batch Runner' to run tests 4). Run or Execute Test Batches from Test Batch Runner. 5) View Test wise Result in 'Test Result Viewer'. Note: QTP 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

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 Operating system compatibility Mobile browsing Printing options

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: 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 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: 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.