working with qtp
TRANSCRIPT
![Page 1: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/1.jpg)
WORKING WITH QTP Functional Test with QTP
Sunday, May 3, 2009
FIND CELL Value in EXCEL VB
Some Time we have to Check that particular Cell Value Exist or Not and required the Cell addressrem this function return the first find Cell address value of your Excel sheet & Change Color of Cell find valuerem input parameter xlFilePath := xls file path || FindValue =value which need to be finddim sXLpath , FindValue ,getCellAddresssXLpath =”C:\RajivKumarNandvani.xls” rem define xls file pathFindValue =”Rajiv” rem check rajiv in cell exist or notgetCellAddress = FindCellAddress(sXLpath ,FindValue )msgbox getCellAddress
Public function FindCellAddress(Byval xlFilePath ,byval FindValue )
Set ObjAppExcel = CreateObject(”Excel.Application”)rem Disable alertsObjAppExcel.DisplayAlerts = Falserem Add a workbook to the Excel AppObjAppExcel.Workbooks.open(xlFilePath)REm Get the object of the first sheet in the workbookSet objectSheet = ObjAppExcel.Sheets(”Sheet1″)rem define the range from A1 to last column address and filnd the value in rangeset objValueFind = objectSheet.UsedRange.Find(FindValue)If not objValueFind is nothing ThenCellAddress =objValueFind.addressFindCellAddress=replace(objValueFind.address,”$”,”")FindCellAddress=replace( FindCellAddress,”1″,”")
Do
set objValueFind = objectSheet.UsedRange.FindNext(objValueFind )
Loop While Not objValueFind Is Nothing And objValueFind.Address <> CellAddress
Exit function
![Page 2: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/2.jpg)
End Ifrem if not found then return the EmptyFindCellAddress=”NOT FOUND”
Set objValueFind =nothingSet objectSheet =nothingSet ObjAppExcel =nothingEnd Function Posted by RajivKumarNandvani at 4:56 AM 0 comments Labels: CELLADDRESS, EXECL, FIND CELL VALUE, SHEET, USEDRANGE
Get EXCEL COLUMN VB / in Array
sXLpath =”C:\TESTXML\Rajiv.xls”myArray = GetALLColumn(sXLpath)
Public function GetALLColumn(Byval xlFilePath )rem define array columnDim AllColumn()Set ObjAppExcel = CreateObject(”Excel.Application”)rem Disable alertsObjAppExcel.DisplayAlerts = Falserem Add a workbook to the Excel AppObjAppExcel.Workbooks.open(xlFilePath)‘Get the object of the first sheet in the workbookSet objectSheet = ObjAppExcel.Sheets(”Sheet1″)rem count used Column in sheetnColumnCount =objectSheet.UsedRange.Columns.Count
ReDim preserve AllColumn(nColumnCount-1)For i=0 to nColumnCount-1AllColumn(i) =objectSheet.Cells(1,i+1).value
Next
GetALLColumn =AllColumnSet objectSheet =nothingSet ObjAppExcel =nothingEnd Function
Posted by RajivKumarNandvani at 4:53 AM 0 comments Labels: ARRAY., cloumn, EXCEL, VB EXCEL
Select Radio Button QTP
![Page 3: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/3.jpg)
Rem**************************************************************************************
Rem This function select the radio button with specified number of indexREM Input objRadiobutton:= radiobutton object intenetexplorer exe || nIndex:= number of specifed radio button which need to be rem selectREM Output(ReturnType) := NoneREM Created: 07/April/2009 Rajiv Kumar Nandvani ## REM Changed:MM/DD/YYYY
REM***************************************************************************
set objRadiobutton =Browser(”Browser”).Page(”Page”)..WebRadio(”Radio_Group”)
nIndex =1 rem first radio button select
call fn_RadioButtonSelect(objRadiobutton,nIndex)
Public Function fn_RadioButtonSelect( byref objRadiobutton,byval nIndex)
sItems= objRadiobutton.GetROProperty(”all items”)sItems=split(sItems,”;”)nIndex =nIndex-1
If nIndex =< (ubound(sItems) ) ThenobjRadiobutton.select sItems(nIndex)elsePrint “Please check number of radio button”
End If
Rem Clear All the Refrences to the ObjectsSet objRadiobutton =nothingEnd Function
Posted by RajivKumarNandvani at 4:49 AM 0 comments Labels: GetROProperty, QTP, radio button
Work With text box( Windows WinEdit box) QTP
In most cases, double-clicking on a data input field is the preferable method of selection; furthermore, it is usually necessary versus a single mouse click on the object. Double –clicking selects the all of the data in that field so that it can be replaced with the new data. A single- click operation, may only place the cursor in the input control , selecting none of the existing data and normally activates the insert mode . Not good. The existing data is not replaced with the new
![Page 4: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/4.jpg)
value. In some applications where multiple words or value separated by spaces can lives in a single edit box. We have found the even double-clicking may not get all of the text selected and ready for replacement. In this case, the method that consistently ensures that all of the data is selected is this: navigate to control via keyboard control, such as tabbing, right arrow or mouse click. Once the cursor is placed into the control, record these keystrokes:
Ctrl + HomeCtrl + Shift + EndDelete
LikeDialog(”Login”).WinEdit(”Agent Name:”).Type micCtrlDwn + micHome + micCtrlUpDialog(”Login”).WinEdit(”Agent Name:”).Type micCtrlDwn + micShiftDwn + micEnd + micShiftUp + micCtrlUp
Posted by RajivKumarNandvani at 4:48 AM 0 comments
Work With List Box QTP
When we use list box Object in QTP. QTP perform following operation on listbox . like
Browser(”Browser”).Page(”Page”)..WebList(”ListBox”).Select “ListBoxValue”
It select the value from List Box that value must be present in list box otherwise QTP give an error like that
“Cannot identify the specified item of the ListBox object. Confirm that the specified item is included in the object’s item collection.”
So before selection any value in list box Always insure the value you are going to select in list box must be present by use this method/Function
dim objListBox, sValuematch ,bTrueset objListBox = Browser(”Browser”).Page(”Page”)..WebList(”ListBox”)sValuematch =”Type Value that need to be check”bTrue = fn_Valuematch_for_weblistbx(objListBox ,sValuematch )if bTrue =True thenBrowser(”Browser”).Page(”Page”)..WebList(”ListBox”).Select “ListBoxValue”end if
REM*************************************************************************************************************REM ” this function Check the value u define match With in WEBListbox or Not if match return true otherwise FalsePublic Function fn_Valuematch_for_weblistbx(byval m_listboxobject, byval m_valuematch)”check is m_listboxobject object or not
![Page 5: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/5.jpg)
If IsObject(m_listboxobject ) = true and IsNull(m_valuematch) = false ThenDim m_Getallfield,m_arAllfield,m_val,m_actualm_arAllfield = m_listboxobject.GetROProperty(”all items”)m_arAllfield =Split (m_arAllfield,”;”)For each element in m_arAllfieldIf m_valuematch = element then ‘ compare the textfn_Valuematch_for_weblistbx=true ” if value match then return true & exit thr loopexit forelsefn_Valuematch_for_weblistbx = falseend ifNextelseprint “Error wrong Parameter for function fn_Valuematch_for_listbx”,”Check paramenter value”End IfEnd FunctionREM***************************** Posted by RajivKumarNandvani at 4:29 AM 0 comments Labels: ListBox, QTP, WebList
Performance increase in table lookup functions QTP
Using object properties instead of QTP standard functions will improve the performance of QTP tests significantly. In our case, we often want to lookup the location of a certain value in a WebTable. QTP provides several functions to read out data from a table, but is slow when used iterating the table (like two for loops, one iterating the rows, the embedded second one iterating the columns per row).
Example of a conservative way to do this:
Public Function LocateTextInTable(byRef tbl, textToFind, byRef row, byRef col)
For row = 1 to tbl.RowCountFor col = 1 to tbl.ColCountIf tbl.GetCellData(row, col) = textToFind thenLocateTextInTable = TrueExit functionEnd ifNextNext
row = -1 : col = -1LocateTextInTable = FalseEnd Function
![Page 6: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/6.jpg)
The crux is this: .GetCellData is not a very fast method and with a table, consisting of 30 rows and 10 columns, this method is iterated up to 300 times in the most worse case scenario (= text not found).
A faster way to retrieve the data is through the Document Object Model (DOM). This allows you to use the more native properties of an object with the sacrifice of some ease of use.
A table consists of row elements and each row element contains one or more cells. We can iterate them just the same way as we did with the function above:
Public Function LocateTextInTableDOM(byRef tbl, textToFind, byRef row, byRef col)
Dim objRow, objCell
row = 1 : col = 1
For each objRow in tbl.object.RowsFor each objCol in objRow.CellsIf objCol.Value = textToFind thenLocateTextInTableDOM = TrueExit functionEnd ifcol = col + 1Nextrow = row + 1Next
row = -1 : col = -1LocateTextInTableDOM = FalseEnd Function
Posted by RajivKumarNandvani at 4:18 AM 0 comments Labels: EXCEL, For loop, QTP, WebTable
Importance of Parenthes when we call Function or Sub QTP
Whenever you define a function with using argument always define the argument type by using ByVal OR ByRef Because if u not define the argument type by default it take ByRef
Parenthesis matter in QTP (and VBScript). And they surely make a difference. During debugging a function call. There was different behaviour between these two function calls:foo(bar)call foo(bar)Passing an argument to a function surrounded by parenthesis means: “Protect me” or in other words: treat me as byVal even if it is defined in the function as byRef.
![Page 7: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/7.jpg)
Example:sub samplesub (a, b) ‘ a and b are by default handled as byRefa = a + bend sub
And this is happening when we call samplesub:x = 1y = 2z = 4samplesub x, ysamplesub (z), ymsgbox x ‘ displays “3″msgbox z ‘ displays “4″ because z was passed as if it was passed byVal
The same applies when you call a function:
function samplefunc(c)c = c^2-1samplefunc = (c mod 2 = 1)end function
q = 8samplefunc qmsgbox q ‘ returns 63
‘ When you accidentally forgot to call:p = 9samplefunc(p)msgbox p ‘ returns 9, because p is returned byVal
‘ With call:r = 10call samplefunc(r)msgbox r ‘ returns 99, because r is returned byRef
‘ With call and argument protected:s = 11call samplefunc( (s) )msgbox s ‘ returns 11, s is returned byVal
‘ And a last example of a function call with multiple argument with combined protection:call multifunc( (IamProtected), IamUnprotected )
Rules in short:A sub/function call with an argument in protected mode overrides a byRef in the function.A sub/function call with an argument in unprotected mode is returned byRef by default unless it
![Page 8: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/8.jpg)
is overridden in the function by a byVal.An literal or const is always returned byVal.
Syntax proposal:OK, it is ugly, but if you use parenthesis because they are part of the call, you should use them with spaces between the first and last argument and no space between the function:
call f( a, b )
If you want to use arguments in protected mode, you should use no spaces between the parenthesis and the arguments, but do use them between the function/sub and the parenthesis belonging to the function/sub call:
f (a), (b)orcall f( (a), (b) )
Delete Cookies and Temprary internet files VB QTP
rem ********************************
rem delete cookies
call fn_DeletesubFolderAndFiles(”C:\DOCUME~1\%USERNAME%\Cookies”)
rem *********************************
rem rem delete Temporary internet files
call fn_DeletesubFolderAndFiles(”C:\DOCUME~1\%USERNAME%\Locals~1\Tempor~1″)
rem ***********************************
REM *************************************************************************
REM Function fn_DeletesubFolderAndFiles(path)
Rem this Function delete the files & subfolder under the specified path
REM Input spath := Files path or parent Folder path
REM Output(ReturnType) := None
REM Note := IF file Protected then it will not delete without giving Error
![Page 9: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/9.jpg)
REM Created: 17/April/2009 Rajiv Kumar Nandvani ## Changed:MM/DD/YYYY
REM *************************************************************************
Public Function fn_DeletesubFolderAndFiles(spath)
on Error Resume Next
rem Create File System object
set objFileSystem = CreateObject(”Scripting.FileSystemObject“)
rem Create Window Shel object
Set objWshShell = CreateObject(“WScript.Shell“)
Rem get Folderpath under which file present
Set objoFolder = objFileSystem.GetFolder(objWshShell.ExpandEnvironmentStrings(spath))
rem get count the files under the folder and loop run for delete the files
For Each oFile In objoFolder.files
On Error Resume Next
objFileSystem.DeleteFile oFile
Err.clear
Next
rem get count the subfolders under the folder and loop run for delete the subfolders
For Each oSubFolder In objoFolder.SubFolders
On Error Resume Next
objFileSystem.DeleteFolder oSubFolder
Err.clear
Next
rem clear the object
![Page 10: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/10.jpg)
set objFileSystem = nothing
set objWshShell = nothing
set objoFolder = nothing
Err.clear
End function
Posted by RajivKumarNandvani at 5:14 AM 0 comments Labels: Cookies, CreateObject("scripting.filesystemobject"), FileSystemObject, Shell, Temporary internet files, WScript.Shell
Close All open Browser QTP VB
‘ This function Close All open BrowserREM *************************************************************************
REM this function close All open browser
Public Function fn_CloseAllBrowser()While Browser(”CreationTime:=0″).ExistBrowser(”CreationTime:=0″).CloseWendEnd Function
REM *************************************************************************ss
Posted by RajivKumarNandvani at 5:12 AM 0 comments Labels: QTP, WEB
Close Application Process QTP
REM This function kill the given process exe through task managerrem example call fn_CloseApplication(”EXCEL.EXE”)
Public Function fn_CloseApplication( byval sApplicationExe)Dim strComputerDim objWMIServiceDim colProcessesDim objProcessstrComputer = “.”Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)
![Page 11: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/11.jpg)
Set colProcesses = objWMIService.ExecQuery (”Select * from Win32_Process Where Name = ‘”&sApplicationExe&”‘”)For Each objProcess in colProcessesobjProcess.Terminate()NextSet objWMIService = NothingSet colProcesses=NothingEnd Function
Posted by RajivKumarNandvani at 5:04 AM 0 comments Labels: Win32_Process, wmiservice
Get current DATETIME through VB QTP/Create unique file or folder
Some Time we want create a folder Or File with unique name then we current date time value for creating the file or folder that we can use this method for create the file OR folder as decribed here
REM this function return the current date time in text format
REM Function fn_GetDateTimeText() This function return currentdatetime in Text formatREM this will remove the specail charactor from currentdatetime & replace with _ underscoreREM Input := NoneREM Output(ReturnType) := return currentdatetime in Text format
Public Function fn_GetDateTimeText
Dim sDateTimesDateTime = nowsDateTime =replace(sDateTime,”:”,”_”)sDateTime =replace(sDateTime,”>”,”_”)sDateTime =replace(sDateTime,”<”,”_”)sDateTime =replace(sDateTime,”/”,”_”)sDateTime =replace(sDateTime,”|”,”_”)sDateTime =replace(sDateTime,”\”,”_”)sDateTime =replace(sDateTime,”*”,”_”)sDateTime =replace(sDateTime,”"”",”_”)sDateTime =replace(sDateTime,”#”,”")fn_GetDateTimeText =sDateTimeEnd Function
dim sGetCurrentDateTime
sGetCurrentDateTime = fn_GetDateTimeText()
Set objFSO =CreateObject(”Scripting.FileSystemObject”)
![Page 12: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/12.jpg)
rem create text file
objFSO.CreateTextFile(“c:/” & sGetCurrentDateTime & “.txt” , True)
rem create folder
objFSO.CreateFolder(“c:/” & sGetCurrentDateTime & “.txt” , True)
Posted by RajivKumarNandvani at 5:02 AM 0 comments Labels: CreateObject("scripting.filesystemobject"), CreateTextFile, date, NOW, QTP, reateFolder, time
Check XML File Valid OR Not VB QTP
REM ************************************************Rem This Function Check XML File Valid OR not if File not valid XML then return False Else TrueREM Function fn_CheckXMLValid( sXMLfilepath)REM Input sXMLfilepath := XMLfilepathREM Output(ReturnType) := True or FalseREM Created: 21/April/2009 Rajiv Kumar Nandvani ## Changed:MM/DD/YYYY
REM *************************************************************************
Public Function fn_CheckXMLValid(byval sXMLfilepath)rem create XML objectSet xmlDoc = CreateObject( “Microsoft.XMLDOM” )xmlDoc.Async = “False”Rem load XML FilexmlDoc.Load( sXMLfilepath )If xmlDoc.parseError.errorCode<>0 Thenfn_CheckXMLValid=Falseelsefn_CheckXMLValid=TrueEnd IfSet xmlDoc = nothing
End Function
REM ************************************************
Posted by RajivKumarNandvani at 5:00 AM 0 comments Labels: CreateObject( "Microsoft.XMLDOM" ), QTP, VB, XML
Get Column Address Excel VB / Find Column
![Page 13: Working With Qtp](https://reader036.vdocuments.site/reader036/viewer/2022082623/546d6eedb4af9f40388b4ffb/html5/thumbnails/13.jpg)
Some Time we have to Check that particular column Exist or Not abd required the column addressrem this function return the column address of your Excel sheetrem input parameter xlFilePath := xls file path || FindColumn =column value which need to be checkdim sXLpath , FindColumn ,getColumnAddresssXLpath =”C:\RajivKumarNandvani.xls” rem define xls file pathFindColumn =”Rajiv” rem check rajiv in column exist or notgetColumnAddress = FindColumnAddress(sXLpath ,FindColumn )msgbox getColumnAddressPublic function FindColumnAddress(Byval xlFilePath ,byval FindColumn )
Set ObjAppExcel = CreateObject(”Excel.Application”)rem Disable alertsObjAppExcel.DisplayAlerts = Falserem Add a workbook to the Excel AppObjAppExcel.Workbooks.open(xlFilePath)‘Get the object of the first sheet in the workbookSet objectSheet = ObjAppExcel.Sheets(”Sheet1″)rem count used Column in sheetnColumnCount =objectSheet.UsedRange.Columns.Countrem get the last column addressc =replace(objectSheet.Cells(1,nColumnCount).address,”$”,”")rem define the range from A1 to last column address and filnd the value in rangeset objValueFind = objectSheet.Range(”A1:”&c).Find(FindColumn)If not objValueFind is nothing ThenFindColumnAddress =replace(objValueFind.address,”$”,”")FindColumnAddress =replace(FindColumnAddress,”1″,”")Exit function
End Ifrem if not found then return the EmptyFindColumnAddress =”NOT FOUND”
Set objValueFind =nothingSet objectSheet =nothingSet ObjAppExcel =nothingEnd Function