QTP学习笔记1

QTP中获取当前路径

实属转帖,方便以后查找~

QTP9.2版本,以下内容适合QTPvbs

路径一:QTP的测试当前路径
environment("TestDir")
使用environment("TestDir")能获取当前测试的绝对路径,不包括最后的“\”
方法:
Path = environment("TestDir")

路径二:QTP安装目录下bin目录的路径
WshShell.CurrentDirectory
(注:不包括地址最后的“/”
方法:
Dim WshShell,path
Set WshShell = WScript.CreateObject("WScript.Shell")
Path = WshShell.CurrentDirectory
以上为vbs中的用法,如果是在QTP中使用,则可以用以下方法(vbs也可以用以下方法):
Dim WshShell,path
Set WshShell = CreateObject("WScript.Shell") ‘就这一句少了“WScript”
Path = WshShell.CurrentDirectory
注意:此方法在QTP运行时获取的将是QTP安装目录下bin目录的路径,如果是写在vbs文件中,然后加载到QTP中,在QTP运行时也是获取QTP安装目录下bin目录的路径。但是如果是编辑一个测试脚本(脚本里包含此获取路径方法,或引用的vbs文件包含此获取路径方法),然后保存(不要关闭脚本),这时运行脚本,则此方法将获取测试脚本存放的当前路径。关闭脚本再打开运行,则还是会获取QTP安装目录下bin目录的路径。因此在调试时可能是正常的,但到运行时就出错了。
   而如果用environment("TestDir"),则获取的都是当前测试的存放路径,但是不能用在VBS文件中(除非此文件是加载到QTP中运行的,那就可以)。
例:QTP安装目录下的bin路径:C:\program files\Mercury Interactive\QuickTest Professional\bin

路径三:vbs文件的路径
left(Wscript.ScriptFullName,len(Wscript.ScriptFullName)-len(Wscript.ScriptName)) 
(注:包括地址最后的“/”
方法:
Path = left(Wscript.ScriptFullName,len(Wscript.ScriptFullName)-len(Wscript.ScriptName))
注意:此方法只能用在单独的vbs文件中,加载到QTP中的vbs文件如果含有此方法也会报错。因为QTP不支持WScript

 


SystemUtil对象的具体用法

1、SystemUtil.BlockInput在执行脚本的过程中锁住键盘和鼠标
SystemUtil.BlockInput
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").WebEdit("userName").Set "mercury"
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").WebEdit("password").SetSecure "4082986e39ea469e70dbf8c5a29429fe138c6efc"
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Image("Sign-In").Click 2, 2
SystemUtil.UnblockInput

2、CloseDescendentProcesses关闭qtp打开的所有进程

SystemUtil.Run "Notepad.exe"
MsgBox SystemUtil.CloseDescendentProcesses

3、object.CloseProcessByHwnd (hWnd)

关闭一个具体句柄指定的窗口

hWnd = Window("Notepad").GetROProperty("hwnd")可以通过GetROProperty("hwnd")这个函数获得窗口句柄SystemUtil.CloseProcessByHwnd (hWnd)
4、object.CloseProcessById (wdProcessId)
通过进程号pid关闭相应的窗口

PID = Window("Notepad").GetROProperty("process id")
    SystemUtil.CloseProcessById (PID)
5、object.CloseProcessByName (bsProcessName)

通过名字来关闭进程例子

SystemUtil.Run "Notepad.exe"
SystemUtil.Run "Notepad.exe"
SystemUtil.Run "Notepad.exe"
MsgBox SystemUtil.CloseProcessByName("Notepad.exe")
6、object.CloseProcessByWndTitle (bsTitle, [bRegExp])
关闭所有窗口包含title文字的进程

bregexp若为true表示title被当作一个正则表达式处理 默认为false
7、隆重出场 run

object.Run file, [params], [dir], [op], [mode]

Argument Description
object A test object of type SystemUtil.
file Required. A String value. The name of the file you want to run. 
params Optional. A String value. If the specified file argument is an executable file, use the params argument to specify any parameters to be passed to the application. 
dir Optional. A String value. The default directory of the application or file. 
op Optional. A String value. The action to be performed. If this argument is blank ( ""), the open operation is performed.
The following operations can be specified for the op argument: Operation
 Description
 
open  Opens the file specified by the FileName parameter. The file can be an executable file, a document file, or a folder. Non-executable files are open in the associated application. 
edit  Launches an editor and opens the document for editing. If the FileName argument does not specify an editable document file, the statement fails. 
explore  Explores the folder specified by the FileName argument. 
find  Initiates a search starting from the specified folder path. 
print  Prints the document file specified by the FileName argument. If the specified file is not a printable document file, the statement fails. 
 
mode Optional. An Integer value.
Specifies how the application is displayed when it opens. You can specify one of the modes in the table below.
Default = 1

Mode
 Description
 
0  Hides the window and activates another window. 
1   Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. Specify this flag when displaying the window for the first time. 
2   Activates the window and displays it as a minimized window. 
3   Activates the window and displays it as a maximized window. 
4   Displays the window in its most recent size and position. The active window remains active. 
5   Activates the window and displays it in its current size and position. 
6   Minimizes the specified window and activates the next top-level window in the Z order. 
7   Displays the window as a minimized window. The active window remains active. 
8   Displays the window in its current state. The active window remains active. 
9   Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. Specify this flag when restoring a minimized window. 
10   Sets the show-state based on the state of the program that started the application. 
 

Return Type

 

SystemUtil.Run "C:\type.txt", "", "", ""
Window("Text:=type.txt - Notepad").Type "happy days"
Window("Text:=type.txt - Notepad").Type micAltDwn & "F" & micAltUp
Window("Text:=type.txt - Notepad").Type micLShiftDwn & "S" & micLShiftUp
Window("Text:=type.txt - Notepad").Close


QTP如何获取本地Excel文件的行和列

Set  excel=CreateObject("Excel.Application")
set openexcel=excel.Workbooks.Open("这里输入EXCEL路径")
rowcount =openexcel.ActiveSheet.UsedRange.Rows.Count
Columnscount =openexcel.ActiveSheet.UsedRange.Columns.count
print " 行数:"&rowcount&"  列数:"&Columnscount
openexcel.Close
excel.Quit
set openexcel=nothing
Set  excel=nothing

'若想要获取Excel中指定sheet的行数和列数,函数如下:
Public function getrowandcol(filepath,sheetname)
'函数作用:获取EXCEL指定sheet的行数和列数
'参数说明
'filepath:EXCEL所在路径
'sheetname:需要统计行数和列数的SHEET名称
'用法示例:getrowandcol"D:/qqq.xlsx","sheet1"

Set  excel=CreateObject("Excel.Application")
set openexcel=excel.Workbooks.Open(filepath)
openexcel.WorkSheets(sheetname).Activate
           rowcount =openexcel.ActiveSheet.UsedRange.Rows.Count
           Columnscount =openexcel.ActiveSheet.UsedRange.Columns.count
If openexcel.WorkSheets(sheetname).Cells(1,1 )="" and rowcount=1 and Columnscount=1 then
           print sheetname&"中没有数据"
else
           print sheetname&"的行数为:"&rowcount&"  列数:"&Columnscount
end if
openexcel.Close
excel.Quit
set openexcel=nothing
Set  excel=nothing

End Function

'说明,若sheet中没有数据,则默认为1行1列,可以写个判断语句,避免没有数据时行数和列数显示为1。见函数中红色代码



VBScript/QTP 的常用COM对象列表

众所周知,我们经常在脚本中创建一些对象来实现某些特定的功能。尤其是当我们使用QTP的描述性编程时,需要创建这些对象。

下边是我们经常在QTP或VBScript中用到的对象列表:

Set objEmail = CreateObject("CDO.Message" )

Set objIE = CreateObject("InternetExplorer.Application" )

Set objInet = CreateObject("InetCtls.Inet.1" )

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1" )

Set objExcel =CreateObject("Excel.Application" )

Set objOutlook = CreateObject("Outlook.Application" )

Set objPpt = CreateObject( "PowerPoint.Application")

Set objWord = CreateObject("Word.Application" )

Set objCal = CreateObject("MSCAL.Calendar" )

Set objQPro = CreateObject("QuattroPro.PerfectScript")

Set objWP = CreateObject("WordPerfect.PerfectScript”")

Set objConn = CreateObject("ADODB.Connection" )

Set objRecSet = CreateObject("ADODB.Recordset" )

Set objDic = CreateObject("Scripting.Dictionary")

Set objFSO = CreateObject("Scripting.FileSystemObject" )

Set wshNetwork = CreateObject("WScript.Network" )

Set wshShell = CreateObject("WScript.Shell")

Set objRandom = CreateObject("System.Random" )

Set objArrList = CreateObject("System.Collections.ArrayList")

Set objSortList = CreateObject("System.Collections.SortedList" )

Set xmlDoc = CreateObject( "Microsoft.XmlDom")

Set xml2Doc = CreateObject("Msxml2.DOMDocument.5.0")

Set objiTunes = CreateObject("iTunes.Application")

Set objPlayer = CreateObject("WMPlayer.OCX" )

Set objWMPlayer = CreateObject("WMPlayer.OCX.7" )

Set objReal = CreateObject( "rmocx.RealPlayerG2 Control.1")

Set objFSDialog = CreateObject("SAFRCFileDlg.FileSave")

Set objFODialog = CreateObject("SAFRCFileDlg.FileOpen" )

Set objDialog = CreateObject("UserAccounts.CommonDialog")

Set SOAPClient = CreateObject("MSSOAP.SOAPClient")

Set objWOL = CreateObject("UltraWOL.ctlUltraWOL")

Set objSearcher = CreateObject("Microsoft.Update.Searcher")

Set objShell = CreateObject("Shell.Application")

SetobjDeviceReplay=CreateObject("Mercury.DeviceReplay")

以下是示例演示:

描述:创建和返回一个自动化对象的引用

语法: CreateObject(class)

class 参数使用了语法servername.typename

servername: 提供对象的应用程序的名称

typename: 对象的类型或类

说明:每个自动化对象至少提供一种对象类型。例如,一个文字处理程序可能会提供一个应用程序对象,一个文件对象和一个工具栏对象。要创建一个自动化对象,需要把CreateObject创建的对象变量赋给一个对象变量。

示例1:创建一个Excel应用程序对象 (“Excel.Application” )

'关闭桌面上打开的所有Excel表格

Systemutil.CloseProcessByName"excel.exe"

'创建一个新的Excel对象

Set Excel =CreateObject("Excel.Application")

'打开Excel表格

Set SExcelSheet =Excel.Workbooks.Open("C:\Users\djiao\Documents\ella\CR_Report.xlsx")

'设置表格可见

SExcelSheet.Application.visible=true

'关闭任何Excel的错误窗口或提示信息

Excel.DisplayAlerts = False

'重命名并保存Excel到不同的路径下

SExcelSheet.SaveAs"C:\BaseLine.xlsx"

'关闭Excel的表格

SExcelSheet.Close

'退出Excel应用程序

Excel.Quit

示例3A: 创建文件系统对象 (“Scripting.FileSystemObject”)

'将要创建的文件夹的存放路径

strDrive = "D:\DATA"

'要创建的文件夹名称

strfoldername= "New Folder"

'获取文件夹的绝对路径

strPath=strDrive&"\"&strfoldername

'创建 FileSystemObject 对象

Set objFSO =CreateObject("Scripting.FileSystemObject")

'文件夹不存在时,创建文件夹

If NOT objFSO.FolderExists(strPath) Then

  objFSO.CreateFolder strPath

End If

'释放文件系统对象

Set objFSO = nothing

示例3B:

'Get the name of file extention

msgbox GetAnExtension("C:\ProgramFiles (x86)\HP\QuickTest Professional\bin\QTPro.exe")

Function GetAnExtension(DriveSpec)

         Dimfso

         Setfso = CreateObject("Scripting.FileSystemObject")

         GetAnExtension= fso.GetExtensionName(Drivespec)

         Setfso = nothing

End Function

示例4: 邮件发送对象(“CDO.Message”)

Dim objMessage

'创建邮件发送对象

Set objMessage =CreateObject("CDO.Message")

'给邮件添加主题

objMessage.Subject = "QTP Results –Automated Testing"

objMessage.From ="[email protected]" ' 改为你自己的邮箱地址

objMessage.To = "[email protected]"'收件人邮箱地址

objMessage.CC = "[email protected]"'CC to email id

'邮件内容

objMessage.TextBody ="N.B. – Please DoNot Reply This Message Directly."

'添加附件

objMessage.AddAttachment"D:\Data\file.text"

'这部分提供了远程SMTP server的配置信息

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")= 2

'设置SMTP server的name或IP

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")= "smtp.163.com"

'服务器端口号(通常是 25)

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")= "someserver.domain.com"

objMessage.Configuration.Fields.Update

'发送邮件

objMessage.Send

'释放邮件对象

Set objMessage = nothing

示例5: 创建WshShell对象 (“Wscript.Shell”)

说明:WScript.Shell是WshShell对象的ProgID,创建WshShell对象可以运行程序、操作注册表、创建快捷方式、访问系统文件夹、管理环境变量。

Set WshShell =CreateObject("Wscript.Shell")

Dim Response

'显示一个带有yes和no的消息框

Response = MsgBox("Please Select yourchoice as ‘Yes’ or ‘No’.", vbYesNo)

If Response = vbYes Then

         '消息框会显示3秒钟

         WshShell.Popup"You Have Been Selected “Yes”. Please wait.", 3, "YourSelection"

Else

         '消息框会显示5秒

         WshShell.Popup"You Have Been Selected “No”", 5, "Your Selection"

End If

Set WshShell = nothing

示例6A: Mercury.DeviceReplay对象  (“Mercury.DeviceReplay”)

说明:这个对象用来模拟鼠标的单击和移动、键盘输入等。使用该对象前,需要保证键盘状态正确,如NUMLOCK是否打开等,DeviceReplay不能检测键盘状态。

'定义坐标

Dim abs_x, abs_y

abs_x = 200

abs_y = 200

'创建Mercury.DeviceReplay对象

Set objMercuryMouse = CreateObject("Mercury.DeviceReplay")

'移动鼠标到指定坐标

objMercuryMouse.MouseMove abs_x,abs_y

'鼠标左击

objMercuryMouse.MouseClick abs_x,abs_y,LEFT_MOUSE_BUTTON

Wait 3

'释放Mercury.DeviceReplay对象

Set objMercuryMouse = nothing

示例7:字典对象(“Scripting.Dictionary”)

'创建dictionary对象

Dim d

Set d =CreateObject("Scripting.Dictionary")

'给dictionary添加key和value

d.Add "a","Athens"  

d.Add "b", "Belgrade"

d.Add "c", "Cairo"

'获取所有的item

a = d.Items

For i = 0 To d.Count -1 ' Iterate thearray.

  s =s & a(i) & VBCrLF ' Create return string.

Next

print s

'根据key获取item

print d.Item("a")

'释放dictionary对象

Set d = nothing

Example 8A: Connection对象,数据集对象("ADODB.Connection")/("ADODB.Recordset")

Function database()

         v_DBInstance= "RENPCRT8"

         v_MHXMLDBPwd= "grudge"

         v_MHXMLDBSchema= "Mhxmledit"

         '创建数据库连接对象和数据集对象

         ConstadOpenStatic = 3

         ConstadLockOptimistic = 3

         ConstadUseClient = 3

         SetobjConnection = CreateObject("ADODB.Connection")

         SetobjRecordset = CreateObject("ADODB.Recordset")

         objConnection.Open"DRIVER={Microsoft ODBC for Oracle};UID="& v_MHXMLDBSchema&" ;PWD="& v_MHXMLDBPwd & ";SERVER="&v_DBInstance &”;"

         objRecordset.CursorLocation= adUseClient

         objRecordset.CursorType= adopenstatic

         objRecordset.LockType= adlockoptimistic

         objRecordset.Source= "select SOP from MHXML.FIRMS_STG where org_id in 681915"

         ObjRecordset.ActiveConnection= ObjConnection

         '执行查询语句

         ObjRecordset.Open

         IfObjRecordset.recordcount>0 then

                   Field1= ObjRecordset("SOP").Value

                   msgboxField1

         Endif

End Function

Example 8B: (“Database connection withoutADODB.Connection Object”)

此方法可以从数据库中获取值为空或者null的数据

Function GetAttorneyInfo(InField,ALid)

         v_DBInstance="RENPCRT8"

         v_MHXMLDBPwd="creek"

         v_MHXMLDBSchema="lbmgradmin"

         GetAttorneyInfo=""

         '创建数据库连接

         MHXMLconnection_string="DRIVER={MicrosoftODBC for Oracle};UID="& v_MHXMLDBSchema &" ;PWD="&v_MHXMLDBPwd &";SERVER=" & v_DBInstance &";"

         isMHXMLConnected= db_connect ( MHXMLConnection ,MHXMLconnection_string )

         IfisMHXMLConnected=0Then '从表中获取数据

                   v_Exe_SQL2="Selectlength(NVL(" & InField & ",'Data Not Found')) fromlbmgradmin.ilv_vw where ilisting_id = " & ALid

                   setRecSet_SOPInfo_LEN = db_execute_query( MHXMLConnection , v_Exe_SQL2 )

                   d_SOPInfo_Length= db_get_field_value( RecSet_SOPInfo_LEN , 0 , 0 )

                   v_Exe_SQL2="selectsubstr(to_char(NVL(" & InField & ",'Data NotFound')),1," & d_SOPInfo_Length & ") from lbmgradmin.ilv_vwwhere ilisting_id = " & ALid

                   setRecSet_SOPInfo = db_execute_query( MHXMLConnection , v_Exe_SQL2 )

                   RowCnt= db_get_rows_count( RecSet_SOPInfo )

                   IfRowCnt=1Then

                            d_SOPInfo=db_get_field_value(RecSet_SOPInfo , 0 , 0 )

                   else

                            datatable.SetCurrentRow(1)

                            d_SOPInfo=db_get_field_value(RecSet_SOPInfo , 0 , 0 )

                   EndIf

         else

         EndIf

         GetAttorneyInfo=d_SOPInfo

End Function

'打开数据库连接

Function db_connect( byRef curSession,connection_string)

         Dimconnection

         onerror Resume next

         '创建数据库连接对象

         setconnection = CreateObject("ADODB.Connection")

         IfErr.Number <> 0 then

                   db_connect="Error # " & CStr(Err.Number) &" " &Err.Description

                   err.clear

                   ExitFunction

         EndIf

         connection.Openconnection_string

         IfErr.Number <> 0 then

                   db_connect="Error # " & CStr(Err.Number) & " " &Err.Description

                   err.clear

                   ExitFunction

         EndIf

         setcurSession=connection

         db_connect=0

End Function

'关闭数据库连接

Function db_disconnect( byRef curSession )

         curSession.close

         setcurSession = Nothing

End Function

'执行查询语句

Function db_execute_query ( byRefcurSession , SQL)

         setrs = curSession.Execute( SQL )

         setdb_execute_query = rs

End Function

'获取数据集的行数

Function db_get_rows_count( byRef curRS )

         dimrows

         rows= 0

         curRS.MoveFirst

         DoUntil curRS.EOF

         rows= rows+1

         curRS.MoveNext

         Loop

         db_get_rows_count= rows

End Function

Example 8C: (“ADODB.Connection”)/(“ADODB.Recordset”)

此示例从Excel表单中获取数据

'创建数据库连接对象

Dim Get_Field

set connectToDB =CreateObject("ADODB.Connection")

connectToDB.Provider ="Microsoft.Jet.OLEDB.4.0"

connectToDB.Properties("ExtendedProperties").Value = "Excel 8.0"

connectToDB.Open "D:\Documents andSettings\pauldx\Desktop\Data.xls"

strQuery="Select Age from [Data$]WHERE Name ='Joli'"

'创建数据集对象

Set rsRecord =CreateObject("ADODB.Recordset")

rsRecord.Open strQuery,connectToDB,1,1

If rsRecord.RecordCount>0 Then

         fori= 1 to rsRecord.RecordCount

                   Get_Field=rsRecord.Fields(0)

                   printGet_Field

                   rsRecord.movenext

         next

Else

         Get_Field="FieldNot Present"

End If

Example 9:("AcroExch.App"/"AcroExch.AVDoc")

此段代码可以从pdf 文件中搜索Software单词

备注:这段代码只有当你安装了acrobat 专业版安装的时候才可以使用。如果只安装了adobe 阅读器的标准版,你会看到如下报错“ActiveX component can’t create object: ‘AcroExch.PDDoc””

Option Explicit

Dim accapp, acavdocu

Dim pdf_path, bReset, Wrd_count

pdf_path="C:\test.pdf"

'创建AcroExch i应用程序对象

Setaccapp=CreateObject("AcroExch.App")

accapp.Show()

'创建AVDoc对象

Setacavdocu=CreateObject("AcroExch.AVDoc")

'打开PDF文件

If acavdocu.Open(pdf_path,"")Then

acavdocu.BringToFront()

bReset=1 : Wrd_count = 0

'查找,定位并高亮指定文本

Do Whileacavdocu.FindText("software", 1, 1, bReset)

bReset=0: Wrd_count=Wrd_count+1

Wait 0, 200

Loop

End If

accapp.CloseAllDocs()

accapp.Exit()

msgbox "The word 'software' was found" & Wrd_count & "times"

Set accap=nothing

Set accapp=nothing

Example 10: .Net 对象("DotNetFactory")

说明:DotNetFactory对象允许创建一个.NET对象,并访问其方法和属性

'创建.Net的form对象

Dim var_CreateInstance

Set var_CreateInstance =DotNetFactory.CreateInstance("System.Windows.Forms.Form","System.Windows.Forms")

'显示form

var_CreateInstance.Show

wait 2

'关闭form

var_CreateInstance.Close

'释放.Net对象

Set var_CreateInstance = nothing





你可能感兴趣的:(QTP学习笔记1)