-
(转) QTP访问外部数据之三:execl文件
2008-12-20 14:40:03
QTP访问外部数据,可以通过把数据存放一个Excel文件当中,然后在脚本当中来访问,当然你也可以通过把Excel文件导入到DataTable当中来,这样使用起来更方便。下面为一些在脚本直接对Excel文件操作的Function Library,可以在QTP安装目录\CodeSamplesPlus下有一个UsingExcel.vbs文件,里面详细的列表出如何对Excel文件进行操作。
' ****************************************** Function Library ***********************************************************
Dim ExcelApp 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Dim excelBook 'As Excel.workbook
Dim fso 'As scrīpting.FileSystemObject
' This function will return a new Excel Object with a default new Workbook
Function CreateExcel() 'As Excel.Application
Dim excelSheet 'As Excel.worksheet
Set ExcelApp = CreateObject("Excel.Application") 'Create a new excel Object
ExcelApp.Workbooks.Add
ExcelApp.Visible = True
Set CreateExcel = ExcelApp
End Function
'This function will close the given Excel Object
'excelApp - an Excel application object to be closed
Sub CloseExcel(ExcelApp)
Set excelSheet = ExcelApp.ActiveSheet
Set excelBook = ExcelApp.ActiveWorkbook
Set fso = CreateObject("scrīpting.FileSystemObject")
On Error Resume Next
fso.CreateFolder "C:\Temp"
fso.DeleteFile "C:\Temp\ExcelExamples.xls"
excelBook.SaveAs "C:\Temp\ExcelExamples.xls"
ExcelApp.Quit
Set ExcelApp = Nothing
Set fso = Nothing
Err = 0
On Error GoTo 0
End Sub
'The SaveWorkbook method will save a workbook according to the workbookIdentifier
'The method will overwrite the previously saved file under the given path
'excelApp - a reference to the Excel Application
'workbookIdentifier - The name or number of the requested workbook
'path - the location to which the workbook should be saved
'Return "OK" on success and "Bad Workbook Identifier" on failure
Function SaveWorkbook(ExcelApp, workbookIdentifier, path) 'As String
Dim workbook 'As Excel.workbook
On Error Resume Next
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
On Error GoTo 0
If Not workbook Is Nothing Then
If path = "" Or path = workbook.FullName Or path = workbook.Name Then
workbook.Save
Else
Set fso = CreateObject("scrīpting.FileSystemObject")
'if the path has no file extension then add the 'xls' extension
If InStr(path, ".") = 0 Then
path = path & ".xls"
End If
On Error Resume Next
fso.DeleteFile path
Set fso = Nothing
Err = 0
On Error GoTo 0
workbook.SaveAs path
End If
SaveWorkbook = "OK"
Else
SaveWorkbook = "Bad Workbook Identifier"
End If
End Function
'The SetCellValue method sets the given 'value' in the cell which is identified by
'its row column and parent Excel sheet
'excelSheet - the excel sheet that is the parent of the requested cell
'row - the cell's row in the excelSheet
'column - the cell's column in the excelSheet
'value - the value to be set in the cell
Sub SetCellValue(excelSheet, row, column, value)
On Error Resume Next
excelSheet.Cells(row, column) = value
On Error GoTo 0
End Sub
'The GetCellValue returns the cell's value according to its row column and sheet
'excelSheet - the Excel Sheet in which the cell exists
'row - the cell's row
'column - the cell's column
'return 0 if the cell could not be found
Function GetCellValue(excelSheet, row, column)
value = 0
Err = 0
On Error Resume Next
tempValue = excelSheet.Cells(row, column)
If Err = 0 Then
value = tempValue
Err = 0
End If
On Error GoTo 0
GetCellValue = value
End Function
'The GetSheet method returns an Excel Sheet according to the sheetIdentifier
'ExcelApp - the Excel application which is the parent of the requested sheet
'sheetIdentifier - the name or the number of the requested Excel sheet
'return Nothing on failure
Function GetSheet(ExcelApp, sheetIdentifier) 'As Excel.worksheet
On Error Resume Next
Set GetSheet = ExcelApp.Worksheets.Item(sheetIdentifier)
On Error GoTo 0
End Function
'The InsertNewWorksheet method inserts an new worksheet into the active workbook or
'the workbook identified by the workbookIdentifier, the new worksheet will get a default
'name if the sheetName parameter is empty, otherwise the sheet will have the sheetName
'as a name.
'Return - the new sheet as an Object
'ExcelApp - the excel application object into which the new worksheet should be added
'workbookIdentifier - an optional identifier of the worksheet into which the new worksheet should be added
'sheetName - the optional name of the new worksheet.
Function InsertNewWorksheet(ExcelApp, workbookIdentifier, sheetName) 'As Excel.worksheet
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
'In case that the workbookIdentifier is empty we will work on the active workbook
If workbookIdentifier = "" Then
Set workbook = ExcelApp.ActiveWorkbook
Else
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
Set InsertNewWorksheet = Nothing
Err = 0
Exit Function
End If
On Error GoTo 0
End If
sheetCount = workbook.Sheets.Count
workbook.Sheets.Add , sheetCount
Set worksheet = workbook.Sheets(sheetCount + 1)
'In case that the sheetName is not empty set the new sheet's name to sheetName
If sheetName <> "" Then
worksheet.Name = sheetName
End If
Set InsertNewWorksheet = worksheet
End Function
'The RenameWorksheet method renames a worksheet's name
'ExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
'sheetName - the new name for the worksheet
Function RenameWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier, sheetName) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Workbook Identifier"
Err = 0
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Worksheet Identifier"
Err = 0
Exit Function
End If
worksheet.Name = sheetName
RenameWorksheet = "OK"
End Function
'The RemoveWorksheet method removes a worksheet from a workbook
'ExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
Function RemoveWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Workbook Identifier"
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Worksheet Identifier"
Exit Function
End If
worksheet.Delete
RemoveWorksheet = "OK"
End Function
'The CreateNewWorkbook method creates a new workbook in the excel application
'ExcelApp - the Excel application to which an new Excel workbook will be added
Function CreateNewWorkbook(ExcelApp)
Set NewWorkbook = ExcelApp.Workbooks.Add()
Set CreateNewWorkbook = NewWorkbook
End Function
'The OpenWorkbook method opens a previously saved Excel workbook and adds it to the Application
'excelApp - the Excel Application the workbook will be added to
'path - the path of the workbook that will be opened
'return Nothing on failure
Function OpenWorkbook(ExcelApp, path)
On Error Resume Next
Set NewWorkbook = ExcelApp.Workbooks.Open(path)
Set ōpenWorkbook = NewWorkbook
On Error GoTo 0
End Function
'The ActivateWorkbook method sets one of the workbooks in the application as Active workbook
'ExcelApp - the workbook's parent excel Application
'workbookIdentifier - the name or the number of the workbook
Sub ActivateWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Activate
On Error GoTo 0
End Sub
'The CloseWorkbook method closes an open workbook
'ExcelApp - the parent Excel application of the workbook
'workbookIdentifier - the name or the number of the workbook
Sub CloseWorkbook(ExcelApp, workbookIdentifier)
On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Close
On Error GoTo 0
End Sub
'The CompareSheets method compares between two sheets.
'if there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'"Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - the excel sheets to be compared
'startColumn - the column to start comparing in the two sheets
'numberOfColumns - the number of columns to be compared
'startRow - the row to start comparing in the two sheets
'numberOfRows - the number of rows to be compared
Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow, numberOfRows, trimed) 'As Boolean
Dim returnVal 'As Boolean
returnVal = True
'In case that one of the sheets doesn't exists, don't continue the process
If sheet1 Is Nothing Or sheet2 Is Nothing Then
CompareSheets = False
Exit Function
End If
'loop through the table and fill values into the two worksheets
For r = startRow to (startRow + (numberOfRows - 1))
For c = startColumn to (startColumn + (numberOfColumns - 1))
Value1 = sheet1.Cells(r, c)
Value2 = sheet2.Cells(r, c)
'if 'trimed' equels True then used would like to ignore blank spaces
If trimed Then
Value1 = Trim(Value1)
Value2 = Trim(Value2)
End If
'in case that the values of a cell are not equel in the two worksheets
'create an indicator that the values are not equel and set return value
'to False
If Value1 <> Value2 Then
Dim cell 'As Excel.Range
sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is '" & Value1 & "'."
Set cell = sheet2.Cells(r, c)
cell.Font.Color = vbRed
returnVal = False
End If
Next
Next
CompareSheets = returnVal
End Function -
(转) QTP访问外部数据之二:环境变量
2008-12-20 14:39:05
QTP的环境变量之中有系统变量和用户自定义变量,环境变量的设置和查看可以可以通过打开(File-settings)Test Settings,在Environment Tab页。系统的环境变量不能增加,修改和删除,用户自定义的,可以增加、修改和删除,同时QTP还提供了,从一个xml文件把符合一定格式的数据导入到QTP的自定义变量当中,所以,在我们需要访问外部数据的时候,也可以通过把数据放到一个xml文件当中,把它作为自定义环境变量,这样,无论在脚本的某一个地方,都可以引用它(环境变量是全局),同时我们也可以修改自定义的环境变量,这样,我们也可以通过用户自定义的环境变量来在脚本当中传递、引用。
到底如何把一个xml文件引用关联到QTP当中来呢?第一可以通过手工在Test Settings的Environment Tab页来设置,还可以在脚本当中,利用Environment的LoadFromFile方法来实现,如下面, Environment.LoadFromFile("C:\QuickTest\Files\MyVariables.xml")
这样就可以把MyVariables.xml文件当中的数据作为用户自定义环境变量来使用了。Environment还有两个属性:一个是Value,一个是ExternalFileName。ExternalFileName表示环境变量引用的外部文件的名称,如何没有引用外部的文件,那么Environment.ExternalFileName的值为一个空的字符串。 -
(转) QTP访问外部数据之一:数据库
2008-12-20 14:35:00
QTP有时候需要访问数据库,以下整理了一些访问数据库常用的FUNCTION
'================================================
'说明:连接数据库
'参数:curSession,数据库连接的指针,用于后面具体访问的操作
'connection_string,连接字符串,如
'connection_string="Provider=MSDAORA.1;Password=password;User ID=user;Data Source=orcl;Persist Security Info=True"
'返回值:0表示连接数据库成功,其它的为出错信息。
'================================================
Function db_connect( byRef curSession ,connection_string)
dim connection
on error Resume next
' 打开连接
set connection = CreateObject("ADODB.Connection")
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Descrīption
err.clear
Exit Function
End If
connection.Open connection_string
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Descrīption
err.clear
Exit Function
End If
set curSession=connection
db_connect=0
End Function
'==============================================
'说明:断开数据库连接
'参数:curSession,数据库连接的指针
'返回值:无
'==============================================
Function db_disconnect( byRef curSession )
curSession.close
set curSession = Nothing
End Function
'===============================================
'说明:通过查询语句,得到一个记录集
'参数:curSession,数据库连接的指针,SQL,相关SQL语句
'返回值:函数返回一个记录集'
'==============================================
Function db_execute_query ( byRef curSession , SQL)
set rs = curSession.Execute( SQL )
set db_execute_query = rs
End Function
'=============================================
'说明:获取记录集的行数
'参数:curRS,记录集的指针
'返回值:返回行数
'===============================================
Function db_get_rows_count( byRef curRS )
On error resume next
dim rows
rows = 0
curRS.MoveFirst
Do Until curRS.EOF
rows = rows+1
curRS.MoveNext
Loop
db_get_rows_count = rows
End Function
'=============================================
'说明:得到记录集当中某一行某一列的值
'参数:curRecordSet,记录集的指针,rowIndex,行的标识,从0开始,
'colIndex,列的标识,从0开始,可以是列名
'============================================
Function db_get_field_value( curRecordSet , rowIndex , colIndex )
dim curRow
curRecordSet.MoveFirst
count_fields = curRecordSet.fields.count-1
If ( TypeName(colIndex)<> "String" ) and ( count_fields < colIndex ) then
db_get_field_value = -1 'requested field index more than exists in recordset
Else
curRecordSet.Move rowIndex
db_get_field_value = curRecordSet.fields(colIndex).Value
End If
End Function
补充说明:数据库连接字符串(连接数据库的时候用到的),可以通过新建一个后缀名为udl的文件,通过该文件完成数据库的连接之后,用文本的方式打开该文件,就可以得到数据库连接的字符串了。 -
(转) QTP中的参数传递
2008-12-20 14:29:01
在QTP的关键字视图中,可以设置ACTION的输入参数和输出参数。设置步骤如下:
1、 选择ACTION名称,然后依此点击“右键——ACTION PROPERTY”,
2、 在弹出的参数设置对话框中,点击“parameters”选项卡,输入ACTJION的输入参数和输出参数
3、 输入完毕后,点击确定按钮,然后利用parameter(“参数名”)即可对参数进行操作。
4、 代码实例:
假设有测试脚本A和B,A中有ACTION1,B中有ACTION2。现在要把ACTION1中的参数传递到ACTION2中。
首先在ACTION1中定义输出参数,依照上述步骤,进入参数设置对话框,在A脚本中新增输出参数outputName,类型为String;然后在action2中定义输入参数inputName。
在关键字视图中,在ACTION2上依次点击“右键——action call property”,在弹出的对话框中点击“parameter values”选项卡,在该选项卡中定义参数变量,界面如图:
在弹出的“values Configration Option”对话框中,选择输入参数为action1的outputName
点击OK按钮后,参数传递的设置就完成了。这时,action1就能把自己的outputName参数传递给 action2,并保存在action2中的inputName参数变量中。
在action1中定义如下代码:
Parameter(“outputName”)=”这是action1的参数”
然后在action2中定义如下代码:
Msgbox parameter(“inputName”)
在QTP中运行脚本,会弹出信息提示框,文字信息为“这是action1的参数 -
(转) QTP:DataTable对象相关的方法
2008-12-20 14:24:22
filename="C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\**\Default.xls"'DataTable存放路径
Par=DataTable.GetSheet("Global").AddParameter("Param1","name1").name'运行时向DataTable添加列,并取得该列名称
print Par
DataTable.GetSheet("Global").SetNextRow'设置下一行
m=DataTable.GetSheet("Global").GetParametercount'取得总列数
DataTable.GetSheet("Global").DeleteParameter ("Param1")'运行时向DataTable删除列
DataTable.GetSheet("Global").SetPrevRow'设置上一行
Parname=DataTable.GetSheet("Global").GetParameter("Destination")'取得某列的值
print Parname
n=DataTable.GetSheet("Global").GetRowCount'取得总行数
DataTable.GetSheet("Global").SetCurrentRow(3)'设置当前行为第3行
DataTable.Value ("Destination", "Global")="New York"'运行时设置某列值 -
(转) QTP实例-记录网站的酒店和房型、价格信息
2008-12-20 14:22:28
1、目标:
获取酒店查询结果中所有的酒店信息,并获取所有房型和价格信息进行记录
2、难点:
a)酒店名称是链接形式,但查询结果界面很多链接,如何过滤出真实的酒店信息链接并获取其名称
b)每个房型的webtable是动态显示的,只有htmlid对于这个webtable是唯一的,需要获取htmlid值来识别对象
c)查询结果分页,每次服务器仅返回当前页面的的信息,翻页后再次获取新的酒店信息,所以取值需要分页进行
3、解决思路:
获取查询结果总页数,循环处理每个页面,在每个页面上获取所有链接的OuterHTML,并结合正则表达式从中提取出酒店名称和酒店ID(处理后作为房型WebTable的唯一识别属性),再获取WebTable中的房型和价格信息,记录在Text中
4、运用技术:
a)DOM
运用getElementsByTagName("A")方法获取界面所有链接集合,并获取每个元素的OuterHTML
b)正则表达式
匹配出符合规则的OuterHTML,并运用Match对象Submatches集合获取OuterHTML中的酒店名称和酒店ID
c)WebTable对象方法
获取酒店的房型和相应的价格
d)FileSystemObject对象
记录所有的酒店、房型和价格信息
5)缺点:
因为链接对象过多,而且进行正则表达式匹配,所以运行速度比较慢,这个需要后续考虑是否有更好的方法进行优化
脚本代码:
'scrīpt Name:GetPrices
,ie(Es%|CL \138711'CreateBy:LiuPei
&i2K\Tm r B1Y~ A138711'CreateTime:2008-07-24
r/Mu5M$Q!~kY4b138711'Descrīption:获取所有酒店信息并列出房型价格
ql3z!Pq138711'————————————————————51Testing软件测试网"z/t L!]1Ka Pl(p
SystemUtil.CloseProcessByName "iexplore.exe"Set IE = CreateObject("Internetexplorer.Application")
3rq6b {CY+O-K138711IE.Visible = True51Testing软件测试网3Er;fr:E+b RfWD
IE.Navigate "http://www.mangocity.com/HWEB/hotelWeb/queryHotelWeb!allForward.action?forward=query"'查询符合条件的酒店51Testing软件测试网)vX N-^Z&\rt]
Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebRadioGroup("res_commonCity").Select "CAN"
)rZ9J5sz7Z4tb/Gy-y138711Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebEdit("queryHotelForWebBean.inDate").Object.value = "2008-07-30"
#D*W%^-Yw:W_138711Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebEdit("queryHotelForWebBean.outDate").Object.value = "2008-07-31"
C;L'j,c+^W138711Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Image("SubmitQuery").Click'获取查询结果页数
-x$\:Pn6[!I2na138711AllItems = Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebList("selectPage2").GetROProperty("all items")
Zg%ZdoVo!D M138711ItemsArr = Split(AllItems , ";")
;L]-P"lYmdy&Q138711PageCount = UBound(ItemsArr) + 1'循环取酒店名称直到所有都完成
rg,u*J m138711For i = 1 to PageCount
E0r-?s},S,Z:ib138711 Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebList("selectPage2").Select ItemsArr(i-1)51Testing软件测试网F#H Q%P5_0RJ
Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Sync'获取酒店信息
qGeC U ~138711 Set ōPage = Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").ObjectFor Each Element in oPage.getElementsByTagName("A")51Testing软件测试网*IDwWN.`sA
TempHtml = Element.outerhtml51Testing软件测试网8i uF*|~
51Testing软件测试网(BUXAR)i"}c4L
'建立正则表达式匹配符合条件的链接字符串51Testing软件测试网'da}o,w)n
Set RegEx = New RegExp51Testing软件测试网3iu2iAK~p*x
RegEx.Pattern = "<A\s*?\w*?\W*?\s*?view_hotel_priceinfo\(.(\d{8})..*?\s*?jpg.\).\s*?href\=.\s*.*?>([^\x00-\xff]*?\W*?[^\x00-\xff]*?\(.*?\))</A>"
u]\Va6g9q138711 RegEx.Global = True
_+Y/zYR#L2C138711 RegEx.IgnoreCase = True51Testing软件测试网ESs BY9pVrd.e
Set matches=RegEx.execute(TempHtml)'获取酒店名称
8`Ss;c nX#JS138711 For each match in matches
$R8P Zf.c[rWQ138711 Hotelid = match.submatches(0)51Testing软件测试网(g{.bS0d/\J3m.X-J
HotelName = match.submatches(1)'记录酒店信息51Testing软件测试网 p ?:Qp)wi
Call WriteHotelInfo(HotelName , "D:\HotelInfo.txt")'房型WebTable的htmlid唯一,采用该属性识别WebTable51Testing软件测试网c _L{ iXwnFb
id = "hotel" & Hotelid
`c1v7@7b3\7_VD$T138711
!^P5F$J$EP4jf/G138711 '获取房型和价格
R/zqA3J `E138711 Set ōWebTable = Browser("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").Page("芒果网 - 酒店预订 机票预订 旅游度假 邮轮").WebTable("html id:="&id)51Testing软件测试网3paYN d9ZT?
NumOfRow = oWebTable.RowCount()
l/Fj9IZ%]:^t4m1O(MX6f138711 For j = 1 to NumOfRow
H|cm9Zv5[ H138711 '获取房型
eg"G3r(B/].~|4^138711 Room = oWebTable.GetCellData(j , 1)
Q$X1e Z["u(F\5Mw138711 Arr = Split(Room , chr(32))
9IZ{@rww$K138711 RoomType = Arr(Lbound(Arr))51Testing软件测试网%N9u,pgp,A^.CA
'获取价格51Testing软件测试网L?K#g!`!eh_ bB
RoomPrice = oWebTable.GetCellData(j , 4)'记录房型价格信息
T%_4@!T xL2O.rE138711 Call WriteRoomInfo(RoomType , RoomPrice , "D:\HotelInfo.txt")51Testing软件测试网,f.E1_lZ9k*I
Next
B,L#F4s!p138711 Next
X7VS,S2M vgB(B7R138711 Set RegEx = Nothing51Testing软件测试网4x X_+M3D|MH
Next
{+r,r'_lHra"R138711Next
7cF!^.K.W/H.q c)_S138711Set IE= Nothing'写入酒店名称
ok:\$o5Z2pk2T138711Function WriteHotelInfo(Hotel , FilePath)51Testing软件测试网&tf.D~ E V8ICj!m
Set fso = CreateObject("scrīpting.FileSystemObject")51Testing软件测试网:[o!r!W[+E2E.Y
8f z7vRoGy5j%w138711 Const ForAppending = 8
7X"?5NH5u138711 Set f = fso.OpenTextFile(FilePath , ForAppending , True)
1~9nP8O{ r8ji;Q!g3b138711 f.WriteLine "------------------" & Hotel & "------------------" & vbCrLf
HO0y#XC-B[w138711
I&AMXi#V&s138711 f.Close51Testing软件测试网-Ej#tIg'E
Set f = Nothing
n.SZg6j+m4?!r138711 Set fso = Nothing51Testing软件测试网$d,g1]/T/|hzr
End Function'写入房型价格信息51Testing软件测试网'w"v}B6\8d
Function WriteRoomInfo(Room , Price , FilePath)51Testing软件测试网-r:L cH5}2B [+|
Set fso = CreateObject("scrīpting.FileSystemObject")
r2K l!}(V"o138711
&\*x(Hn*Kf\138711 Const ForAppending = 8
6X+i'w*Zac i138711 Set f = fso.OpenTextFile(FilePath , ForAppending , True)
)| r}4t&@-{d138711 f.WriteLine Room & "-----------" & Price51Testing软件测试网x$[ ZFK
51Testing软件测试网Pj5f)\'z
f.Close51Testing软件测试网!dF;V0~+Za;W^
Set f = Nothing
:v+oW&xJ a138711 Set fso = Nothing51Testing软件测试网OESH2x1NPta @2t
End Function51Testing软件测试网x(Z4pF8x(mZ(_运行效果:
------------------广东国际大酒店(Guangdong International Hotel)------------------
房型-----------周三
+Ukp:G8v0J e138711标准客房(单自助早)-----------¥480 51Testing软件测试网?;wGpvx+r+b{(i
高级客房(单自助早)-----------¥590
k6z]i$ol138711商务套房(单自助早)-----------¥690 51Testing软件测试网"J0cG W$AG
行政房(单自助早)-----------¥690 51Testing软件测试网+jCJAY
豪华套房(单自助早)-----------¥790 51Testing软件测试网6inx4|/q5o;`Z | ~ Q
行政商务套房(双自助早)-----------¥860 51Testing软件测试网,` _7B!Z9ZS&pr
行政豪华套房(双自助早)-----------¥1010
ZL+D)? t+DCqH Y$K138711------------------广州总统大酒店(Guangzhou President Hotel)------------------房型-----------周三
3M8v+Y1?Y"V m138711舒适间(无早)-----------¥320 51Testing软件测试网Z;HC O,QGG
舒适间(双自助早)-----------¥360
I/WlY)z!N#]~8g8R138711高级间(双自助早)-----------¥408
4mz`3g]ua138711行政间(双自助早)-----------¥498
nv P HR138711商务套房(双自助早)-----------¥648 51Testing软件测试网Y-S%e6{*PXp
行政套房(双自助早)-----------¥788
#Q"IT z3^j%X138711------------------广东南洋长胜酒店(Guangzhou Nanyang King Gate Hotel)------------------房型-----------周三
!T/NK%u2fU-f ?*g138711卢浮宫-标准单人间(含双早)-----------¥300
^%G;M2M;F138711卢浮宫-标准双人间(含双早)-----------¥300
a"HM5]V5TBk1H138711凯旋宫-高级房(含双早)-----------¥380 51Testing软件测试网;i!}.SSi&F E'L
凯旋宫-豪华房(含双早)-----------¥438
Q K_ U^ T138711凯旋宫-豪华商务大床房(含双早)-----------¥568
o2TRB+^:uF138711卢浮宫-行政A一房一厅(含双早)-----------¥600 51Testing软件测试网"w0x|3Z!G-q@]
凯旋宫-豪华套房(含双早)-----------¥950
`+x(l"Zw#MGL!g b2h138711卢浮宫-行政B三房一厅(含双早)-----------¥1600 51Testing软件测试网om DvM5gX
------------------广州鼎龙国际大酒店(Guangzhou Donlord International Hotel)------------------房型-----------周三 51Testing软件测试网6Rc ?@_Z A-v
舒适房(双自助早)-----------¥380
"Z r6Va*P.Bf)l138711高级单人房(双自助早)-----------¥438 51Testing软件测试网LW~+K,f1^Bw Pa|
高级双人房(双自助早)-----------¥438 51Testing软件测试网2k(M:QrQ's
豪华房(双自助早)-----------¥550 51Testing软件测试网!wF{ o!He:E o4u
高级套房(双自助早)-----------¥640
*~CR6|#y138711豪华行政客房(双自助早)-----------¥640 51Testing软件测试网0cH0?3?:I'z xm,x ^n%X
豪华套房(双自助早)-----------¥840 -
(转)LoadRunner 技巧篇
2008-12-20 12:15:05
性能测试是一件非常严谨的事情,很多人在做性能测试的时候只是关注工具如何去用而很少关心如何去做好性能测试的准备,建模等工作。以下是在性能测试中lr模拟的一些常见问题。.网络带宽问题。
对Web进行压力测试时,通常百兆网络是不够的,当网络带宽不够的时候server端没有足够压力。用LoadRunner所在的Windows的性能管理器看一下网络利用率就知道了。
.Vuser脚本的检查。
Loadrunner提供了方便的脚本录制功能,但由于录制时可能出现的操作错误,vuser访问一些不存在的资源。去除某些与压力测试无关的东西。否则可能会出现Loadrunner测试结果有误或压力上不去的情况
.Runtime setting。
在创建Loadrunner scenario时,每台机器的vuser的runtime setting都应该分别设置并检查,不能只对第一个vuser的runtime setting进行设置。通常你会关掉think time,以便能用较少的机器达到较大的压力。另外,如果返回页面里包含了一些访问其它资源的链接比如图片服务器,这时应关掉 download non-html resources。
.没有检查返回页面。
当server端出错时应用程序有可能返回错误信息,但对HTTP来讲仍是成功的响应,返回码为200 O.K. 这样在Loadrunner就被记为成功的transaction。于是,server端出错越多,Loadrunner测出的性能越好。解决办法:开启并检查应用的错误日志;或者启用Loadrunner的返回内容检查功能。
.当心Loadrunner所在机器的磁盘空间。
缺省情况下Loadrunner会把运行结果的详细信息放在C盘的Documment and Settings的用户目录下,当大压力长时间运行或有大量出错时,Loadrunner会生成大量的数据到该目录下。当磁盘空间满了后,机器的响应将变得很慢。
命令行打开LoadRunner
在多个场景需要运行的时候,可以通过批处理循环运行场景,保存结果到指定文件夹:
bat内容:
set LR_HOME=C:\Program Files\Mercury\LoadRunner
for /L %%iScenario in (1,1,10) do "%LR_HOME%\bin\Wlrun.exe" -Run -TestPath "%LR_HOME%\scenario\memory_leak_crash.lrs" -ResultName C:\LR_Result\result%%iScenario. 既可以验证请求的正确性又Vさ玫秸返氖奔?/FONT>
由于lr的http 200的经典错误,所以需要加入验证点,如果加入了验证点,就使事务响应时间大于实际的响应时间,如何解决呢,利用lr_waste_time解决,代码如下。
double time_elapsed, duration, waste;
merc_timer_handle_t timer;
lr_start_transaction("sampleTrans");
web_url("index.htm",
"URL=http://localhost/index.htm",
"TargetFrame=",
"Resource=0",
"RecContentType=text/html",
"Referer=",
"Snapshot=t1.inf",
"Mode=HTML",
LAST);
timer = lr_start_timer();
// Do some checks the duration of which is not to be included in the transaction.
web_image_check("ImgCheck1",
"src=index_files/image002.jpg",
LAST);
web_image_check("ImgCheck2",
"src=index_files/planets.gif",
LAST);
// How long did the tests take in seconds.
time_elapsed = lr_end_timer(timer);
// Convert to millisecond.s
waste = time_elapsed * 1000;
// Remove the time the checks took from the transaction.
lr_wasted_time(waste);
lr_end_transaction("sampleTrans", LR_AUTO); -
(转) 启动应用程序的方式
2008-12-20 12:13:47
常用的启动应用程序的方式
'1.systemutil.Run
SystemUtil.Run "calc.exe"'2.wscrīpt.shell
Dim wsh 'as wcript.Shell
Dim strExe_Path 'as stringstrExe_Path = "calc.exe"
Set wsh=CreateObject("wscrīpt.shell")wsh.Exec strExe_Path
Set wsh=nothing
'3.录制的方式,虽然比较傻,但是很有效Dialog("运行").WinEdit("打开(O):").Set "calc.exe"
Dialog("运行").WinButton("确定").Click
SystemUtil.Run "calc.exe","","C:\Documents and Settings\piaochunlong",""
Window("计算器").Close'4 api方式 难度在于了解win32消息机制
'vb api变换成 QTP的api声明才能用
'Public Declare Function WinExec Lib "kernel32" Alias "WinExec" (ByVal lpCmdLine As String, ByVal nCmdShow As Long) As Long
Extern.Declare micLong,"WinExec","kernel32","WinExec",micString,micLong
Extern.WinExec "calc.exe",5备注:针对最后一种情况提供一个声明转换的工具。
'5 InvokeApplication
InvokeApplication "calc.exe"
-
(转) QTP 函数实现
2008-12-20 12:12:57
Write a program to delete Line in file?
思路:封装scrīpting.filesystemobject对象,利用readline方法
Function DeleteLine(strFile, strKey, LineNumber, CheckCase)
'Use strFile = "c:\file.txt" (Full path to text file)
'Use strKey = "John Doe" (Lines containing this text string to be deleted)
'Use strKey = "" (To not use keyword search)
'Use LineNumber = "1" (Enter specific line number to delete)
'Use LineNumber = "0" (To ignore line numbers)
'Use CheckCase = "1" (For case sensitive search )
'Use CheckCase = "0" (To ignore upper/lower case characters)Const ForReading=1:Const ForWriting=2
Dim objFSO,objFile,Count,strLine,strLineCase,strNewFile
Set ōbjFSO=CreateObject("scrīpting.FileSystemObject")
Set ōbjFile=objFSO.OpenTextFile(strFile,ForReading)
Do Until objFile.AtEndOfStream
strLine=objFile.Readline
If CheckCase=0 then strLineCase=ucase(strLine):strKey=ucase(strKey)
If LineNumber=objFile.Line-1 or LineNumber=0 then
If instr(strLine,strKey) or instr(strLineCase,strkey) or strKey="" then
strNewFile=strNewFile
Else
strNewFile=strNewFile&strLine&vbcrlf
End If
Else
strNewFile=strNewFile&strLine&vbcrlf
End If
Loop
objFile.Close
Set ōbjFSO=CreateObject("scrīpting.FileSystemObject")
Set ōbjFile=objFSO.OpenTextFile(strFile,ForWriting)
objFile.Write strNewFile
objFile.CloseEnd Function
-
(转) QTP Scripting - 实践10
2008-12-20 12:11:30
Write a program to comparing text files?
Sub Main
fileName1 = "x:\text1.txt"
fileName2 = "x:\text2.txt"
If CompareFiles(fileName1, fileName2) Then
Msgbox "The files are equal"
Else
MsgBox "The files are different"
End If
End Sub
Function CompareFiles(fileName1, fileName2)
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
'Creates the FileSystemObject object
Set fso = CreateObject("scrīpting.FileSystemObject")
'Reads the first text file
Set file1 = fso.OpenTextFile(fileName1, ForReading)
fileText1 = file1.ReadAll
file1.Close
'Reads the second text file
Set file2 = fso.OpenTextFile(fileName2, ForReading)
fileText2 = file2.ReadAll
file2.Close
'Creates the regular expression object
Set regEx = New RegExp
'Specifies the pattern for the date/time mask
'MM/DD/YYYY HH:MM:SSLL (for example: 4/25/2006 10:51:35AM)
regEx.Pattern = "\d{1,2}.\d{1,2}.\d{2,4}\s\d{1,2}:\d{2}:\d{2}\w{2}"
regEx.IgnoreCase = True
regEx.Global = True
'Replaces the text matching the specified date/time format with <ignore>
newText1 = regEx.Replace(fileText1, "<ignore>")
newText2 = regEx.Replace(fileText2, "<ignore>")
'Compares the text
If newText1 = newText2 Then
CompareFiles = True
Else
CompareFiles = False
End If
End Function -
(转) QTP Scripting - 实践9
2008-12-20 12:10:34
Write a program to Dynamically adding to WebList ?
思路:html dom 技术
脚本代码:
Dim objDoc
Dim objElement
Dim newNode
Set ōbjDoc = Browser("Browser").Page("Page").Object
Set ōbjElement = objDoc.GetElementByID("WebList")
Set newNode = objDoc.createElement("option")
newNode.Text = "Test——pcl"
objElement.add newNode
Set newNode = Nothing
Set ōbjElement = Nothing
Set ōbjDoc = Nothing -
(转) QTP Scripting - 实践8
2008-12-20 12:09:59
write a program to Highlight a object?
思路:利用api函数实现
代码:
Extern.Declare micHwnd, "GetDesktopWindow", "User32.DLL", "GetDesktopWindow"
Extern.Declare micULong, "GetWindowDC", "User32.DLL", "GetWindowDC", micHwnd
Extern.Declare micInteger, "ReleaseDC", "User32.DLL", "ReleaseDC", micHwnd, micULong
Extern.Declare micULong, "CreatePen", "Gdi32.DLL", "CreatePen", micInteger, micInteger, micDword
Extern.Declare micInteger, "SetROP2", "Gdi32.DLL", "SetROP2", micULong, micInteger
Extern.Declare micULong, "SelectObject", "Gdi32.DLL", "SelectObject", micULong, micULong
Extern.Declare micULong, "DeleteObject", "Gdi32.DLL", "DeleteObject", micULong
Extern.Declare micULong, "GetStockObject", "Gdi32.DLL", "GetStockObject", micInteger
Extern.Declare micULong, "Rectangle", "Gdi32.DLL", "Rectangle", micULong, micInteger, micInteger, micInteger, micInteger
Function HighlightRect (X, Y, W, H, Times)hDC = Extern.GetWindowDC (Extern.GetDesktopWindow)
hPen = Extern.CreatePen (6, 3, RGB(0, 0, 0)) ' PS_INSIDEFRAME, 3 , RGB(0, 0, 0)
Extern.SetROP2 hDC, 6 ' hDC, R2_NOT
Extern.SelectObject hDC, hPen
Extern.SelectObject hDC, Extern.GetStockObject (5)
For i = 0 to Times * 2 + 1
Extern.Rectangle hDC, X, Y, X + W, Y + H
wait 0, 50
Next
Extern.ReleaseDC Extern.GetDesktopWindow, hDC
Extern.DeleteObject hPenEnd Function
-
(转) QTP Scripting - 实践7
2008-12-20 12:03:32
思路:利用 cmo和 outlook对象
解决方法1:
Dim Outlook 'As New Outlook.Application
Set ōutlook = CreateObject("Outlook.Application")
Dim Message 'As Outlook.MailItem
Set Message = Outlook.CreateItem(olMailItem)
With Message
.Subject ="hello"
.Body = "test\"
'Set destination email address
.Recipients.Add ("pcl@51testing.com")
.Send
End With
解决方法2:Dim Email As Object
NameS = "http://schemas.microsoft.com/cdo/configuration/"
Set Email = CreateObject("CDO.Message")
Email.From = "****@qq.com" '//你自己的油箱号码
Email.To = "" ' // 要发的人
Email.Subject = "" '//相当于邮件里的标题
Email.Textbody = "" '//相当于邮件里的内容
Email.Configuration.Fields.Item(NameS & "sendusing") = 2
Email.Configuration.Fields.Item(NameS & "smtpserver") = "smtp.qq.com" '// 服务器
Email.Configuration.Fields.Item(NameS & "smtpserverport") = 25 '//端口号
Email.Configuration.Fields.Item(NameS & "smtpauthenticate") = 1
Email.Configuration.Fields.Item(NameS & "sendusername") = "**" '//油箱号码@前面的名字
Email.Configuration.Fields.Item(NameS & "sendpassword") = "**" '//你油箱的密码
Email.Configuration.Fields.Update
Email.Send -
(转) QTP Scripting - 实践6
2008-12-20 12:01:04
write a program to Saving a file from IE?思路: 利用MSXML4里面提供了一个可用的新的组件:WinHttp.WinHttpRequest.5.1
技术主要利用在下载文件验证方面。下面是我做个下载我上传的一个文件的测试,除了WinHttp.WinHttpRequest.5.1对象还利用到了ado.stream对象,进行保存文件处理。
代码如下:
Set WinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
If WinHttp Is Nothing Then Set WinHttp = CreateObject("WinHttp.WinHttpRequest")
WinHttp.Open "GET", "http://www.51testing.com/batch.download.php?aid=10479", False
WinHttp.Send
arrArray = WinHttp.ResponseBody
Set WinHttp = Nothing
On Error Resume Next
Set ōADO = CreateObject("ADODB.Stream")
If oADO Is Nothing Then
Set ōFSO = CreateObject("scrīpting.FileSystemObject")
Set ōTextFile = oFSO.OpenTextFile("c:\a.rar", 2, True)
sData = ""
sBuffer = ""
For iCount = 0 to UBound(arrArray)
oTextFile.Write Chr(255 And Ascb(Midb(arrArray,iCount + 1, 1)))
Next
oTextFile.Close
Else
oADO.Type = 1
oADO.Open
oADO.Write arrArray
oADO.SaveToFile "c:\a.rar", 2
oADO.Close
End If
Set ōADO = Nothing
Set ōTextFile = Nothing
Set ōFSO = Nothing -
(转) QTP Scripting - 实践5
2008-12-20 12:00:37
针对论坛问题进行实战,在论坛寻找没有被解决的问题进行实战代码演练,问题如下
http://bbs.51testing.com/thread-119326-1-2.html
这里面问题的难点主要利用ado如何读取数据库大二进制流的数据,如何把图片插入到excel中
ado需要利用的方法: GetChunk
功能:
返回大型文本或二进制数据 Field 对象的全部或部分内容。
语法
variable = field.GetChunk( Size )
返回值
返回变体型。
参数
Size 长整型表达式,等于所要检索的字节或字符数。
说明
使用 Field 对象的 GetChunk 方法检索其部分或全部长二进制或字符数据。在系统内存有限的情况下,可使用 GetChunk 方法处理部分而非全部的长整型值。
GetChunk 调用返回的数据将赋给“变量”。如果 Size 大于剩余的数据,则 GetChunk 仅返回剩余的数据而无需用空白填充“变量”。如果字段为空,则 GetChunk 方法返回 Null。
每个后续的 GetChunk 调用将检索从前一次 GetChunk 调用停止处开始的数据。但是,如果从一个字段检索数据然后在当前记录中设置或读取另一个字段的值,ADO 将认为已从第一个字段中检索出数据。如果在第一个字段上再次调用 GetChunk 方法,ADO 将把调用解释为新的 GetChunk 操作并从记录的起始处开始读取。如果其他 Recordset 对象不是首个 Recordset 对象的副本,则访问其中的字段不会破坏 GetChunk 操作。
如果 Field 对象的 Attributes 属性中的 adFldLong 位设置为 True,则可以对该字段使用 GetChunk 方法。
如果在 Field 对象上使用 Getchunk 方法时没有当前记录,将产生错误 3021(无当前记录)。解决问题代码:
sub main
save_pic
insert_Excel_pic
end subSub Save_Pic()
Dim DcnNWind 'As ADODB.Connection
Dim rs 'As ADODB.Recordset
set DcnNWind=New ADODB.Connection
Set rs = New ADODB.Recordset
DcnNWind.CursorLocation = adUseClient
DcnNWind.Open "Provider=SQLOLEDB.1;Integrated Security=SSI;Persist Security Info=False;InitialCatalog=CUSTOM;Data Source=SERVER"
rs.CursorType = adOpenKeyset
rs.LockType = adLockOptimistic
rs.Open "CustomInfo", DcnNWind, , adCmdTable
rs.Move 第几行数据 '指针指向到第几行数据
Call BlobToFile (rs.Fields("Image"), "c:\windows\temp\tmp.bmp", rs.Fields("Image").ActualSize)End Sub
Sub BlobToFile(fld , FileName, Optional ChunkSize )
Dim fnum , bytesLeft , bytes
Dim tmp() 'As Byte
If (fld.Attributes And adFldLong) = 0 Then
Err.Raise 1001, , "Field doesn't support the GetChunk method."
End If
If Dir$(FileName) <> "" Then Kill FileName
fnum = FreeFile
Open FileName For Binary As fnum
bytesLeft = fld.ActualSize
Do While bytesLeft
bytes = bytesLeft
If bytes > ChunkSize Then bytes = ChunkSize
tmp = fld.GetChunk(bytes)
Put #fnum, , tmp
bytesLeft = bytesLeft - bytes
Loop
Close #fnum
end sub
Sub insert_Excel_pic()
Set ōbjExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
objExcel.Range("A1").Select
objExcel.ActiveSheet.Pictures.Insert("C:\a.bmp").Select
'处理Excel
set ōbjExcel=Nothing
End Sub -
(转) QTP Scripting - 实践4
2008-12-20 11:59:59
Write a program to read and delete cookies?
关键点在于常识:cookies所存放的文件夹位置
Set fso = CreateObject("scrīpting.FilesystemObject")
set wshNetwork = CreateObject("Wscrīpt.Network")
struser = wshNetwork.UserName
fso.DeleteFile "C:\DOCUMENTS AND SETTINGS\" & struser & "\COOKIES\*.*",Force
fso.DeleteFile "C:\DOCUMENTS AND SETTINGS\" & struser & "\LOCAL SETTINGS\TEMP\*.*",Force
fso.DeleteFile "C:\DOCUMENTS AND SETTINGS\" & struser & "\LOCAL SETTINGS\TEMPORARY INTERNET FILE\*.*",Force
fso.DeleteFile "C:\WINNT\TEMP\*.*",Forceset fso=nothing
set wshNetwork=nothingwhat a Limitations of DataTable QTP?
Maximum worksheet size—65,536 rows by 256 columns
Column width—0 to 255 characters
Text length—16,383 characters
Formula length—1024 characters
Number precision—15 digits
Largest positive number—9.99999999999999E307
Largest negative number— -9.99999999999999E307
Smallest positive number—1E-307
Smallest negative number— -1E-307
Maximum number of names per workbook—Limited by available memory
Maximum length of name—255
Maximum length of format string—255
Maximum number of tables (workbooks)—Limited by system resources (windows and memory) -
(转) QTP Scripting - 实践3
2008-12-20 11:59:14
工具只是自动化测试的手段,完全可以利用其他方式来编写脚本自动化,今天的自动化脚本实现的目标是Write a program to List all links in the web page?
Write a program to Check whether given link exists?
以上两个问题其实很类似,只不过是后面稍微变化了下,我们来看下代码的实现,根据第一个例子的解决方法实现第二个解决方法
程序1
问题1解决方法:
Dim oAnchors
Dim oAnchorSet ōAnchors = Browser(X).Page(X).WebTable(X).Object.GetElementsByTagName("A") '获得页面的所有链接
For Each oAnchor in oAnchors
msgbox oAnchor.innertext
Next 'oAnchorSet ōAnchors = Nothing
问题2解决方法
Dim oAnchors
Dim oAnchor
Dim blnFoundSet ōAnchors = Browser(X).Page(X).WebTable(X).Object.GetElementsByTagName("A")
blnFound = False
For Each oAnchor in oAnchors
If oAnchor.innertext = "Whatever" Then
oAnchor.Click()
blnFound = True
End If
Set ōAnchor = Nothing
If blnFound = True Then Exit For
Next 'oAnchorSet ōAnchors = Nothing
实际问题应用:2006年在论坛上有位广州的朋友问得一个问题
QuickTestPro处理带有IFRAME的问题原问题链接:http://bbs.51testing.com/viewthread.php?tid=35723&extra=page%3D1
解决问题的答案: http://www.51testing.com/html/27/1566.html
http://www.51testing.com/html/27/1565.html
思考题:利用dom技术解决以上问题
项目实际问题延伸:
对比页面table表格中的数据,利用ado读取数据库内容,然后对比页面实际数据,页面扫描cell代码如下:
Dim objRows
Dim objRow
Dim objCells
Dim objCell
Dim blnFound
Dim lngCellCountSet ōbjRows = Browser(X).Page(X).WebTable(X).Object.GetElementsByTagName("TR")
blnFound = False
lngCellCount = 0For Each objRow in objRows
Set ōbjCells = objRow.GetElementsByTagName("TD")
For Each objCell in objCells
If objCell.InnerText = "需要查找的内容,可以利用数据库读取的数据对比" Then
'可以打印报告 你可以按照自己的意愿自己处理
End If
Set ōbjCell = NothingNext 'objCell
Set ōbjCells = Nothing
Set ōbjRow = Nothing
Next 'objRowSet ōbjRows = Nothing
-
(转) QTP Scripting - 实践2
2008-12-20 11:58:33
今天培训的内容是关闭特定程序,这里特定程序是browser,涉及到的知识点有com,可描述性编程,虽然有些难度,老婆还是很快搞定了,希望老婆再接再厉。
Write a program to close all browsers from QTP?
思路:解决问题 关闭ie所有的进程 利用dp的方法关闭
程序1:利用Systemutil的方式关闭
systemutil.CloseProcessByName "IEXPLORE.EXE"
程序2:利用wmi关闭
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill
strComputer = "."
strProcessKill = "'IEXPLORE.EXE'"Set ōbjWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
NextSet ōbjWMIService=Nothing
程序3:
利用QuickTest Professional Descrīptive Programming.动态处理Browser
Do While Browser("CreationTime:=0").Exist
Browser("CreationTime:=0").Close
Loop思考题:利用api的方式关闭特定的进程
-
(转) QTP Scripting - 实践1
2008-12-20 11:57:44
Write a program to enter data in login screen
思路:1.录制程序 2.增强脚本进行数据驱动
程序1:
systemutil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").WinEdit("Agent Name:").Set "lytester"
Dialog("Login").WinEdit("Password:").SetSecure "48743575b1759f8f151c2d2741124daec13d6e7d"
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close程序2:
数据驱动:文件数据驱动,利用FSO对象'文件格式
'111111,mercury
'22222,mercuryDim fso
Dim f
'......
Dim s_User
Dim s_Pwd
Dim arrTempSet fso=CreateObject("scrīpting.filesystemobject")
Set f=fso.OpenTextFile("路径",1,false)Do while f.atEndOfLine<>true
s_Temp=f.ReadLine
arrTemp=split(s_Temp,",")
s_User=arrTemp(0)
s_Pwd=arrTemp(1)
systemutil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").WinEdit("Agent Name:").Set s_User
Dialog("Login").WinEdit("Password:").Set s_Pwd
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
loopf.close
set f=nothing
set fso=nothing思考题目:实现数据驱动脚本包含登陆的所有成功和失败的情况
2 Write a program to find the x and y coordinates of a buttonDim x
Dim ysystemutil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
x=Dialog("Login").WinButton("OK").GetROProperty("x")
y=Dialog("Login").WinButton("OK").GetROProperty("y")
msgbox "x:"+cstr(x)+";y:"+cstr(y)思考题目:API方式
3 Write a program to Read items in a list box
思路:利用VB addin 识别对象后利用getcontent方法实现
Dim sContent 'as string
Dim MyArray ' this is a array
Dim strMsg 'as stringsContent = VbWindow("Form1").VbList("List1").GetContent()
MyArray = split( sContent ,vbLf)For i=LBOUND(MyArray) to UBound(MyArray)
strMsg=strMsg+MyArray(i)
NextMsgBox strMsg
思考题:利用Api方式获得
-
(转) QTP的Action间的信息共享的4种方法
2008-12-20 11:54:50
通过Action参数来传递数据
Action2的脚本如下:
' Input Parameters
Message = Parameter("Msg")
Msgbox Message
' Output Parameters
If NOT Message = "" Then
Parameter("ReturnMsg") = "The Message is " & Message
Else
Parameter("ReturnMsg") = "The Message is Empty!"
End If
' RetuenValue
ExitAction "HAHAHAHHAHA!!!!!"
'ExitAction Parameter("ReturnMsg")
3种调用Action的方法,Action1的脚本如下:
' 调用Action2,输入参数为 “ Hello!”,把输出参数值写到ReturnMessage1变量
RunAction "Action2", oneIteration,"Hello!" ,ReturnMessage1
Msgbox ReturnMessage1
' 调用Action2,输入参数为 “ Hello!”,通过Parameter方法读取输出参数值
RunAction "Action2", oneIteration,"Hello!"
ReturnMessage2= Parameter("Action2","ReturnMsg")
Msgbox ReturnMessage2
' 如果被调用的Action使用了ExitAction来退出Action并返回ReturnValue,则可以使用下面的方式来获取Return Value的值
' 注意OutPut Parameters与Return Value的区别
ReturnMessage3 = RunAction( "Action2", oneIteration ,"Hello!")
Msgbox ReturnMessage3
通过全局数据表(Global Data Table)来共享数据
在Action1中设置参数值,Action1的脚本如下:
' 获取全局数据表
Set Sheet = DataTable.GetSheet("Global")
' 查找参数列
Set Parameter1 = Sheet.GetParameter("Column1")
Set Parameter2 = Sheet.GetParameter("Column2")
' 设置参数值
Parameter1.Value="Hello"
Parameter2.Value="World!"
' 调用Action2,Action2将使用前面设置的参数值
RunAction "Action2", oneIteration
在Action2中读取参数值,Action2的脚本如下:
' 获取全局数据表
Set Sheet = DataTable.GetSheet("Global")
' 读取参数值
Set Parameter1 = Sheet.GetParameter("Column1")
Set Parameter2 = Sheet.GetParameter("Column2")
' 使用参数值
Msgbox Parameter1 &" " & Parameter2
使用环境变量(Environment Variables)来共享数据
在Action1中使用环境变量中定义的LoginUserName和LoginPassWord,Action1的脚本如下:
' 在Action1中使用环境变量中定义的LoginUserName和LoginPassWord
UserName = Environment.Value("LoginUserName")
UserPassWord = Environment.Value("LoginPassWord")
SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set UserName
Dialog("Login").WinEdit("Password:").SetSecure UserPassWord
Dialog("Login").WinButton("OK").Click
' 调用Action2,在Action2中也将使用到定义的环境变量
RunAction "Action2", oneIteration
在Action2中使用环境变量中定义的LoginUserName,Action2的脚本如下:
' 在Action2中使用环境变量中定义的LoginUserName
UserName = Environment.Value("LoginUserName")
Window("Flight Reservation").Activate
Window("Flight Reservation").WinObject("Date of Flight:").Click 1,6
Window("Flight Reservation").WinObject("Date of Flight:").Type "121212"
Window("Flight Reservation").WinComboBox("Fly From:").Select "Denver"
Window("Flight Reservation").WinComboBox("Fly To:").Select "Frankfurt"
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "14243 DEN 12:57 PM FRA 01:41 PM SR $110.00"
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set UserName
通过Dictionary对象来在Action之间共享数据
(1)添加注册表
HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects\GlobalDictionary
ProgID = "Scripting.Dictionary"
(2)使用GlobalDictionary对象
' 使用GlobalDictionary前清空里面的数据
If GlobalDictionary.Count > 0 Then
GlobalDictionary.RemoveAll
End If
' 存储一个数值
DepartDate = "2008-3-31"
GlobalDictionary.Add "DateCheck", DepartDate
' 可在当前Action使用GlobalDictionary中的数据,也可在另外一个Action中使用添加到GlobalDictionary的数据
'Dim CompareDate
'CompareDate=GlobalDictionary("DateCheck")
'Msgbox CompareDate
' 可在当前Action使用GlobalDictionary中的数据,也可在另外一个Action中使用添加到GlobalDictionary的数据
Dim CompareDate
' 读取GlobalDictionary中的DateCheck数据
CompareDate=GlobalDictionary("DateCheck")
Msgbox CompareDate
标题搜索
我的存档
数据统计
- 访问量: 166985
- 日志数: 260
- 书签数: 81
- 建立时间: 2007-08-28
- 更新时间: 2012-06-13