您的位置:首页 > 编程语言 > Qt开发

QTP汇总比较有价值的脚本

2014-02-04 22:41 435 查看

1、ObjectSpy的Tips

HoldtheCTRLkeytochangethewindowfocusorperformothermouseoperations

2、QTP为什么无法单步调试?

安装MicrosoftScriptDebuger即可

3、QTP如何访问Oracle数据库?

Dimrs,sq,pkey

setconn=createobject("adodb.connection")

setrs=createobject("adodb.recordset")

'需要安装Oracle客户端

conn.open"Provider=OraOLEDB.Oracle.1;PersistSecurityInfo=False;UserID=scott;DataSource=orcl;Password=orcl;ExtendedProperties=;Host=192.168.1.188;Port=1521;ServiceName=orcl;"

sql="SELECT*FROMTAB"

rs.opensql,conn

rs.MoveFirst

DoWhilers.Eof<>true

Msgboxrs.Fields(0)

rs.MoveNext

Loop

rs.close

setrs=nothing

conn.close

setconn=nothing

4、如何全选所有WebCheckBox对象?

DimoWebChkDesc

SetoWebChkDesc=Description.Create

oWebChkDesc("micclass").value="WebCheckBox"

oWebChkDesc("htmltag").Value="INPUT"

'获取所有匹配描述的对象

DimallCheck,oCheckBox

SetallCheck=Browser("WebTours").Page("WebTours").ChildObjects(oWebChkDesc)

Fori=0toallCheck.Count-1

SetoCheckBox=allCheck(i)

oCheckBox.Set"ON"

Next

5、QTP9.2录制脚本问题:运行QTP,点击录制钮进行脚本录制,但是IE浏览器打开后几秒钟,又自动关闭了,不知道为什么?

QTP9.2支持的IE浏览器版本:

MicrosoftInternetExplorer6.0ServicePack1

MicrosoftInternetExplorer7.0

6、Action之间无法传递数组

用全局的Dictionary对象来存储数据,这样可以在多个Action之间共用数据

参考:

http://blog.csdn.net/Testing_is_believing/archive/2010/01/08/5161955.aspx

http://blog.csdn.net/Testing_is_believing/archive/2008/06/09/2528094.aspx

也可以这样:

建一个vbs文件,定义变量,在Setting—>Resources导入这个VBS文件

在主Action里面给变量赋值

在子Action中调用这个变量

这个变量的内存相当于共享

7、QTP脚本编辑器中可以修改Tab键跳转的格数吗?

编辑脚本时,总感觉Tab一次,移动的格数太少

Tools->ViewOptions

8、如何在VBScript中调用QTP脚本

现在有一个用QTP录制好的脚本,但是想用VBS来调用,如何调用?

DimqtApp'AsQuickTest.Application'DeclaretheApplicationobjectvariable

DimqtTest'AsQuickTest.Test'DeclareaTestobjectvariable

DimqtResultsOpt'AsQuickTest.RunResultsOptions'DeclareaRunResultsOptionsobjectvariable

SetqtApp=CreateObject("QuickTest.Application")'CreatetheApplicationobject

qtApp.Launch'StartQuickTest

qtApp.Visible=True'MaketheQuickTestapplicationvisible

'SetQuickTestrunoptions

qtApp.Options.Run.ImageCaptureForTestResults="OnError"

qtApp.Options.Run.RunMode="Fast"

qtApp.Options.Run.ViewResults=False

qtApp.Open"C:\Tests\Test1",True'Openthetestinread-onlymode

'setrunsettingsforthetest

SetqtTest=qtApp.Test

qtTest.Settings.Run.IterationMode="rngIterations"'Runonlyiterations2to4

qtTest.Settings.Run.StartIteration=2

qtTest.Settings.Run.EndIteration=4

qtTest.Settings.Run.OnError="NextStep"'InstructQuickTesttoperformnextstepwhenerroroccurs

SetqtResultsOpt=CreateObject("QuickTest.RunResultsOptions")'CreatetheRunResultsOptionsobject

qtResultsOpt.ResultsLocation="C:\Tests\Test1\Res1"'Settheresultslocation

qtTest.RunqtResultsOpt'Runthetest

MsgBoxqtTest.LastRunResults.Status'Checktheresultsofthetestrun

qtTest.Close'Closethetest

SetqtResultsOpt=Nothing'ReleasetheRunResultsOptionsobject

SetqtTest=Nothing'ReleasetheTestobject

SetqtApp=Nothing'ReleasetheApplicationobject

9、没安装QTP打开QTP脚本的方法

QTP的脚本在每个action的根目录下的Script.mts文件,用UltraEdit或记事本等工具打开就可以看到。

10、QTP支持的正则表达式

使用反斜杠字符(\)

匹配任意单个字符(.)

匹配列表中的任意单个字符([xy])

匹配不在列表中的任意单个字符([^xy])

匹配某个范围内的任意单个字符([x-y])

特定字符的零次或多次匹配(*)

特定字符的一次或多次匹配(+)

特定字符的零次或一次匹配(?)

对正则表达式进行分组(())

匹配几个正则表达式中的一个表达式(|)

在一行的开始进行匹配(^)

在一行的结尾进行匹配($)

匹配包括下划线在内的任一字母数字字符(\w)

匹配任意非字母数字字符(\W)

11、如何判断Excel进程是否存在?

如何判断Excel进程是否存在?如果存在则关闭Excel进程。

SystemUtil.CloseProcessByName"excel.exe"

Onerrorresumenext

DimObj

SetObj=GetObject(,"Excel.Application")

IfNotObjIsNothingThen

Obj.Quit

SetObj=Nothing

EndIf

或者:

'Tokillexcelapplication

CreateObject("WScript.Shell").Run"taskkill/f/imexcel.exe"

'Tocheckifexcelisrunningusethisfunction

msgbox"ExcelisRunning:"&FindProcess("EXCEL.EXE")

FunctionFindProcess(ByValProcessName)

FindProcess=False

SetShell=CreateObject("WScript.Shell")

SetShellResult=Shell.Exec("TaskList")

WhileNotShellResult.StdOut.AtEndOfStream

IfInstr(UCASE(ShellResult.StdOut.ReadLine),UCASE(ProcessName))Then

FindProcess=True

ExitFunction

EndIf

Wend

EndFunction

12、如何在浏览器对象的指定位置按右键?

hwnd=Browser("Browser").GetROProperty("hwnd")

window("hwnd:="&hwnd).Click12,6,micRightBtn

13、怎样在QTP中关闭Windows防火墙?

'DisabletheFirewall

SetobjFirewall=CreateObject("HNetCfg.FwMgr")

SetobjPolicy=objFirewall.LocalPolicy.CurrentProfile

objPolicy.FirewallEnabled=FALSE

SetobjPolicy=Nothing

SetobjFirewall=Nothing

14、如何使用QTP检查电脑中某目录是否存在?

Dimfso,msg,fldr

fldr="D:\books"

Setfso=CreateObject("Scripting.FileSystemObject")

If(fso.FolderExists(fldr))Then

msg=fldr&"exists."

Else

msg=fldr&"doesn'texist."

EndIf

Msgboxmsg

15、QTP菜单丢失的问题

QTP用了一段时间菜单怎么没了呢?

重置一下Toolbars,应该就可以了

16、如何判断注册表HKEY_CURRENT_USER\Software\WinRAR是否存在?

DimWshShell,bKey

SetWshShell=CreateObject("WScript.Shell")

ONErrorResumeNext

bKey=WshShell.RegRead("HKEY_CURRENT_USER\Software\WinRAR\")

'bKey=WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_OraDb10g_home1\ORACLE_HOME_NAME")

IfbKey=vbEmptyThen

Msgbox"KeyNotExists!"

EndIF

SetWshShell=Nothing

17、QTP中怎么测试邮件激活功能时?

测试一个用户注册的功能,注册后会发送一封邮件到注册的邮箱,完了需要用户到邮箱查看,通过一个链接激活后,才算注册成功,这个功能如何用QTP实现自动化?

可下载个JMail组件,然后在QTP中连接邮箱,接收邮件,再分析邮件内容,解析出链接来,然后发送WEB页面请求该链接的URL

附JMail接收邮件的脚本:

Setpop3=CreateObject("JMail.POP3")

pop3.Connect"xxx","xxx","pop.126.com"

Print"邮件总数:"&pop3.Count

Setmsg=pop3.Messages.Item(1)

Printmsg.Subject

Printmsg.FromName

Printmsg.Body

Setpop3=Nothing

18、QTP中如何压缩文件和解压缩文件?

例如在D:\test下面有10个txt文件,文件名分别为1.txt2.txt3.txt依次类推

能否在QTP中先把它们压缩,然后再解压缩?

SetobjWsh=CreateObject("Wscript.shell")

'压缩

objWsh.Run"winraraD:\test\test.rarD:\test\*.txt",0,True

'解压缩

objWsh.Run"winrarx-o+D:\test\test.rar*.txtD:\test\",0,True

SetobjWsh=Nothing

19、如何在QTP中启动网络、断开网络

下面的代码可用于停用和启用网络连接(名字可能需要根据实际的进行修改):

ConstssfCONTROLS=3

sConnectionName="无线网络连接"

sEnableVerb="启用(&A)"

sDisableVerb="停用(&B)"

setshellApp=createobject("shell.application")

setoControlPanel=shellApp.Namespace(ssfCONTROLS)

setoNetConnections=nothing

foreachfolderiteminoControlPanel.items

iffolderitem.name="网络连接"then

setoNetConnections=folderitem.getfolder:exitfor

endif

next

ifoNetConnectionsisnothingthen

msgbox"未找到网络和拨号连接文件夹"

wscript.quit

endif

setoLanConnection=nothing

foreachfolderiteminoNetConnections.items

iflcase(folderitem.name)=lcase(sConnectionName)then

setoLanConnection=folderitem:exitfor

endif

next

ifoLanConnectionisnothingthen

msgbox"未找到'"&sConnectionName&"'item"

wscript.quit

endif

bEnabled=true

setoEnableVerb=nothing

setoDisableVerb=nothing

s="Verbs:"&vbcrlf

foreachverbinoLanConnection.verbs

s=s&vbcrlf&verb.name

ifverb.name=sEnableVerbthen

setoEnableVerb=verb

bEnabled=false

endif

ifverb.name=sDisableVerbthen

setoDisableVerb=verb

endif

next

'debuggingdisplaysleftjustincase...

'

'msgboxs':wscript.quit

'msgbox"Enabled:"&bEnabled':wscript.quit

'notsurewhy,butinvokeverbalwaysseemedtowork

'forenablebutnotdisable.

'

'savingareferencetotheappropriateverbobject

'andcallingtheDoItmethodalwaysseemstowork.

'

ifbEnabledthen

'oLanConnection.invokeverbsDisableVerb

oDisableVerb.DoIt

else

'oLanConnection.invokeverbsEnableVerb

oEnableVerb.DoIt

endif

'adjustthesleepdurationbelowasneeded...

'

'ifyoulettheoLanConnectiongooutofscope

'andbedestroyedtoosoon,theactionoftheverb

'maynottake...

'

wscript.sleep400

20、QTP怎么检测XML文档?

(1)使用XMLUtil对象。

XMLUtil对象用于读取XML文件,其LoadFile方法可从指定的文件中读入XML格式的文本,返回XMLData对象,例如,下面的脚本:

'使用XMLUtil对象的CreateXML方法来创建XMLData对象

Setdoc=XMLUtil.CreateXML()

'加载XML文件用于检查

doc.LoadFile"Test.XML"

可用Validate方法来指定某个Schema文件,检查加载的XML文件是否满足Schema的格式要求,例如,下面的脚本检查对象库导出的XML文件是否满足ObjectRepository.xsd的要求:

'检查XML文档是否满足指定的XMLschema

ans=doc.Validate("D:\ProgramFiles\MercuryInteractive\QuickTestProfessional\dat\ObjectRepository.xsd")

'如果检查满足Schema,则提示检查成功,否则列出不满足的原因

IfansThen

MsgBox"XML文件匹配指定的Schema!"

else

errNo=doc.GetValidationErrorsNumber

Fori=1toerrNo

errStr=doc.GetValidationError(i)

MsgBoxerrStr

Next

EndIf

(2)利用XMLDOM对象来加载XML数据进行分析。

XMLDOM是用来访问和操作XML文档的编程接口规范。XMLDOM被设计为可用于任何语言和任何操作系统。借助DOM,我们可以通过VBScript创建XML文档对象,遍历其结构,增、改、删其元素。DOM将整个XML文档视作一棵树,文档级的元素是树的根。

XMLDOM包含四个主要对象:XMLDOMDocument、XMLDOMNode、XMLDOMNodeList、XMLDOMNamedNodeMap。每个XMLDOM对象有其自己的特性和方法。

下面的例子通过XMLDOM对象加载XML文件,修改指定节点的值,然后保存到另外一个XML文件:

SetxmlDoc=CreateObject("Microsoft.XMLDOM")'创建XMLDOM对象

xmlDoc.async=False

xmlDoc.load"test.xml"'加载XML文档

'检查XML文档是否有错误

IfxmlDoc.parseError.errorCode<>0Then

SetmyErr=xmlDoc.parseError

MsgBox("XMLLoadsFailed."&myErr.reason)

Else

SetrootNode=xmlDoc.documentElement

'修改XML指定节点的某个属性的值

rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue="E-Mail"

PrintrootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue'打印修改后的节点值

rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue="hello!"'修改节点值

PrintrootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue'打印修改后的节点值

'保存xml数据到另外一个文件

xmlDoc.save"test_save.xml"

EndIf

SetxmlDoc=Nothing

21、WEB页面中的Image按钮对象动态变化,在脚本运行时会有问题

http://www.beebuyer.com/c/270-Formal-Special-Occasion-Dresses这个网址,点击“addtocart”后按钮变成“checkcart”就是这个按钮过不去。

这是对象动态变化了

addtocart已经被智能识别出来了,check_cart_icon是后面动态生成的对象,之前加个Wait语句等待它生成即可:

Browser("ChinaWholesaleFormal,").Page("ChinaWholesaleFormal,").Image("addtocart").Click

Wait2

Browser("ChinaWholesaleFormal,").Page("ChinaWholesaleFormal,").Image("check_cart_icon").Click

也可以这样:

DountilBrowser("ChinaWholesaleFormal,").Page("ChinaWholesaleFormal,").Image("check_cart_icon").Exist(2)

Loop

22、QTP连接DB2出现的58004错误提示问题怎么解决?

提示错误:

[IBM][CLIDriver]SQL1042C发生意外的系统错误。SQLSTATE=58004

IhaveaprobleminconnecingQTPtoDB2andfetchqueryresults.

Myscriptgoeslikethis:(samplePOC)

connection_string="Driver={IBMDB2ODBCDRIVER};Database=ecomdb;Hostname=pyro.ecom.com;Port=50000;Protocol=TCPIP;Uid=admin;Pwd=adminqa;"

msgboxdb_connect(curSession,connection_string)

Functiondb_connect(byRefcurSession,connection_string)

dimconnection

onerrorResumenext

'Openingconnection

setconnection=CreateObject("ADODB.Connection")

IfErr.Number<>0then

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

err.clear

ExitFunction

EndIf

connection.Openconnection_string

IfErr.Number<>0then

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

err.clear

ExitFunction

EndIf

setcurSession=connection

db_connect=0

EndFunction

Thisscriptispoppingupthiserrormsg:

[IBM][CLIDriver]SQL1042CAnunexpectedsystemerroroccurred.SQLSTATE=58004

Fortheotherconnectionstringtype,

data_DSN="QAProd"'dsncreatedincontrolpanel

data_usr="admin"

data_pwd="adminqa"

data_alias="ecomdb"'nameofthedatabase

connection_string="DSN="&data_DSN&";""UID="&data_usr&";""PWD="&data_pwd&";""DBALIAS="&data_alias&";"

iamgettingsameerrororanothererrorsaying

passworderror-notabletoreproducewhenpostingthisthread

Icheckedconnectionstrings.comandotherthreadsinthisforumdiscussingaboutQTP-DB2connection,butcouldn'tfindouttheanswerformyproblem.

helpmetountiethisproblem.

--------------------------------------------------------------------------------

ProblemDescription:Error:"[IBM][CLIDriver]SQL1042CAnunexpectedsystemerroroccured.SQLSTATE=58004"

Theuserreceivesa"[IBM][CLIDriver]SQL1042CAnunexpectedsystemerroroccured.SQLSTATE=58004"errormessagewhentryingtoconnecttoanIBMDB2clientusingaDatabaseCheckpointorADODBstatementswithinthescript.

Diagnosis:Theexistenceofthe<QuicktestProfessional>/bin/QTPro.exe.LocalfileconflictswiththeabilityofADODBtoopentheDB2client.

--------------------------------------------------------------------------------

Solution:RenametheQTPro.exe.Localfileinthebindirectory

TheQTPro.exe.LocalfileisusedforredirectionofDLLsthatQuickTestProfessionalloads.InthecaseofcoexistenceproblemswithotherMercuryproducts,thefileinstructsWindowsAPItoloadDLLsfromthe<QuickTestProfessional>\bindirectoryinstead
ofotherdirectories.ThisisimportantforthecoexistencebetweenQuickTestProfessional,LoadRunner,andoldversionsofAstraLoadTest.

Renamingthisfileshouldsolvetheproblem.QuickTestProfessionalwillworkfinewithoutQTPro.exe.Local,unlessLoadRunnerorAstraLoadTestareinstalledonthemachine.

1.CloseQuickTestProfessional.

2.OpenWindowsExplorer,andnavigatetotheQuickTestProfessionalinstallationdirectory.

3.Inthebindirectory,locatetheQTPro.exe.Localfile,andrenameit(forexample,QTPro.exe.Local.old).

4.RestartQuickTestProfessional.

Afterrenamingthefile,QuickTestProfessionalshouldbeabletoconnecttothedatabaseandworkwithitasexpected.Iftheerrorcontinues,tryremovingunneededparametersintheconnectionstring.

23、如何把一个Excel中的Sheet页数据拷贝到另外一个Excel的Sheet页中?

SetobjExcel=CreateObject("Excel.Application")

objExcel.Visible=True

SetobjWorkbook1=objExcel.Workbooks.Open("D:\1.xls")

SetobjWorkbook2=objExcel.Workbooks.Open("D:\2.xls")

objWorkbook1.Worksheets("Sheet1").UsedRange.Copy

objWorkbook2.Worksheets("Sheet2").Range("A1").PasteSpecial'Paste=xlValues

objWorkbook1.Save

objWorkbook2.Save

objWorkbook1.Close

objWorkbook2.Close

objExcel.Quit

setobjExcel=nothing

24、如何设置WinButton的Enable属性为False?

Win类型的对象不支持用SetROProperty这种设置属性的方法

可以用WinAPI中的EnableWindow来设置按钮是否可用。例如:

Extern.DeclaremicInteger,"EnableWindow","user32.dll","EnableWindow",micHwnd,micInteger

windowName="计算器"

hWnd=Extern.FindWindow(null,windowName)

Window("hwnd:="&hwnd).ActivatemicLeftBtn

buttonHwnd=Window("hwnd:="&hwnd).WinButton("text:=1").GetROProperty("hwnd")

Extern.EnableWindowbuttonHwnd,False

25、QTP的Browser对象部分方法失效的问题

部分Browser方法,如Navigate、Back、Home、Refresh等在某些人的机器上是好用的,但在另外一些人的机器上就不好用了。脚本执行到这些方法,并不会抛出错误;而且qtp日志里看到的状态是"done"。

经过观察发现这些机器上IE加载项(IE"工具"->"管理加载项")的不同:

BHOManagerClass插件的问题。文件名是BHOManager.dll,部分人的机器上该插件被禁用或删除掉了,猜测原因可能是使用了某些清理ie的工具导致。

解决该问题的方法很简单:

如果是被禁用了,只要重新启用即可;如果是被删除掉了,可以重新安装qtp,或者从别处拷贝BHOManager.dll文件过来,用regsvr32BHOManager.dll注册后就可以了。

26、如何修改QTP脚本默认打开/保存的目录?

QTP脚本开发,每次都要打开文件夹,却总是默认从C:\ProgramFiles\MercuryInteractive\QuickTestProfessional\Tests来找文件,

默认的目录是可以修改的,只要修改注册表:

1,HKEY_current_user\software\MI\QTP\mictest\TestsDirectory

2,HKEY_local_machine\software\MI\QTP\mictest\TestsDirectory

修改为:

自定义的文件夹

重启QTP即可看到打开文件夹已经修改为自定义的目录

27、如何修改Windows分辨率?

用C#编写一个DLL:

usingSystem;

usingSystem.Runtime.InteropServices;

namespaceScreenDisplaySetting

{

publicclassChangeResulution

{

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]

publicstructDEVMODE

{

[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]

publicstringdmDeviceName;

publicshortdmSpecVersion;

publicshortdmDriverVersion;

publicshortdmSize;

publicshortdmDriverExtra;

publicintdmFields;

publicshortdmOrientation;

publicshortdmPaperSize;

publicshortdmPaperLength;

publicshortdmPaperWidth;

publicshortdmScale;

publicshortdmCopies;

publicshortdmDefaultSource;

publicshortdmPrintQuality;

publicshortdmColor;

publicshortdmDuplex;

publicshortdmYResolution;

publicshortdmTTOption;

publicshortdmCollate;

[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]

publicstringdmFormName;

publicshortdmLogPixels;

publicintdmBitsPerPel;

publicintdmPelsWidth;

publicintdmPelsHeight;

publicintdmDisplayFlags;

publicintdmDisplayFrequency;

}

[DllImport("user32.dll",CharSet=CharSet.Auto)]

staticexternintChangeDisplaySettings([In]refDEVMODElpDevMode,intdwFlags);

[DllImport("user32.dll",CharSet=CharSet.Auto)]

staticexternboolEnumDisplaySettings(stringlpszDeviceName,Int32iModeNum,refDEVMODElpDevMode);

publicvoidChangeRes(intwidth,intheight,intfrequency,intBitsPerPel)

{

DEVMODEDevM=newDEVMODE();

DevM.dmSize=(short)Marshal.SizeOf(typeof(DEVMODE));

boolmybool;

mybool=EnumDisplaySettings(null,0,refDevM);

DevM.dmPelsWidth=width;//宽

DevM.dmPelsHeight=height;//高

DevM.dmDisplayFrequency=frequency;//刷新频率

DevM.dmBitsPerPel=BitsPerPel;//颜色象素

longresult=ChangeDisplaySettings(refDevM,0);

}

}

}

然后在QTP中使用以下脚本来修改分辨率

Setvar_CreateInstance=DotNetFactory.CreateInstance("ScreenDisplaySetting.ChangeResulution","E:\ScreenDisplaySetting.dll")

var_CreateInstance.ChangeRes1024,768,60,32'参数分别代表宽、高、刷新率、颜色质量

Setvar_CreateInstance=Nothing

28、QTP如何上传文件到FTP服务器?

可利用wininet.dll的相关函数来实现:

ConstDEFAULT_FTP_PORT=21

ConstSERVICE_FTP=1

ConstOPEN_TYPE_DIRECT=1

ConstFTP_TRANSFER_TYPE_ASCII=1

Extern.DeclaremicLong,"InternetOpen","wininet.dll","InternetOpenA",micString,micDWord,micString,micString,micDWord

Extern.DeclaremicLong,"InternetConnect","wininet.dll","InternetConnectA",micLong,micString,micInteger,micString,micString,micDWord,micDWord,micDWord

Extern.DeclaremicInteger,"FtpGetFile","wininet.dll","FtpGetFileA",micLong,micString,micString,micInteger,micDWord,micDWord,micDWord

Extern.DeclaremicInteger,"FtpPutFile","wininet.dll","FtpPutFileA",micLong,micString,micString,micDWord

Extern.DeclaremicInteger,"InternetCloseHandle","wininet.dll","InternetCloseHandle",micLong

'打开

hInternet=Extern.InternetOpen("QTP_FTP",OPEN_TYPE_DIRECT,vbNullChar,vbNullChar,0)

IfhInternet=0ThenPrint("QTP_FTP:FailedtosetupFTPenvironment.")

'连接

hConnection=Extern.InternetConnect(hInternet,"www.atstudy.com",DEFAULT_FTP_PORT,"user1","user1",1,0,0)

IfhConnection=0ThenPrint("FailedtosetupFTPenvironment")

'上传

'bRetval=Extern.FtpPutFile(hConnection,sLocalFile,sRemoteFile,0)

'下载

bRetval=Extern.FtpGetFile(hConnection,"/Mercury/QuickTest/QTPcrack.rar","D:\QTPcrack.rar",0,0,1,0)

IfNotCBool(bRetVal)Then

Reporter.ReportEventmicFail,"FTP:FtpGetFilefunction","Failedtoopendownloadfile."

else

Print("FTP:File:QTPcrack.rardownloadedsuccessfully")

'Reporter.ReportEventmicPass,"FTP:FtpPutFilefunction","FTP:File"&sLocalFile&"uploadsuccessfully."

EndIf

'关闭

Extern.InternetCloseHandle(hConnection)

Extern.InternetCloseHandle(hInternet)

29、QTPwebtable单元格赋值问题

在编写QTP代码过程中,对于WEBTABLE类型,不知道怎么赋值

图中黄色区域即是要赋值的区域,操作是先点击,才能变成可写,

可以用SetobjLink=objTable.ChildItem(intRow,intCol,"WebElement",0)获得对象,因为点击后,此单元格变成可写的webedit类型,即objLink这个对象直接set值肯定不行,目前不知道怎么去实现?

SetobjLink=objTable.ChildItem(intRow,intCol,"WebElement",0)

objLink.Click

再用SendKeys或者Mercury.DeviceReplay来发送字符串输入

30、QTP能不能自动加上with...endwith语句?

一大堆代码要手动改成with...endwith语句来提高执行效率,问一下QTP有没有这个功能可以自动修改呢?

Edit-->Advanced-->Apply"With"toscript...

31、关闭多个浏览器窗口

例1

Dimi

i=0

while(Window("Text:=Yahoo!-MicrosoftInternetExplorer","index:="&i).exist)

Window("Text:=Yahoo!-MicrosoftInternetExplorer","index:="&i).close

i=i+1

wend

例2:

DimoBrowserDesc,oBrowsers,iBrowserCount,iBrowserIndex,sBrowserName

SetoBrowserDesc=Description.Create

oBrowserDesc("micclass").Value="Browser"

SetoBrowsers=Desktop.ChildObjects(oBrowserDesc)

iBrowserCount=oBrowsers.Count

IfiBrowserCount=0Then

'Print"当前没有浏览器打开"

Else

'Print"浏览器个数:"&cStr(iBrowserCount)

ForiBrowserIndex=0ToiBrowserCount-1

'sBrowserName=oBrowsers(iBrowserIndex).getroproperty("name")

'Print"正在关闭:"&sBrowserName

oBrowsers(iBrowserIndex).Close

Next

EndIf

SetoBrowsers=Nothing

SetoBrowserDesc=Nothing

参考:

http://relevantcodes.com/qtp-closing-multiple-browser-windows/

http://relevantcodes.com/qtp-working-with-multiple-browser-applications-revised/

32、描述性编程时,QTP无法识别带问号的网址URL?

需要对?号进行转义:

PageURL="http://bbs.51testing.com/frame.php?frameon=yes"

Browser("version:=inter.*").NavigatePageURL

IfBrowser("version:=inter.*").Page("url:=http://bbs.51testing.com/frame.php\?frameon=yes").ExistThen

Print"OK"

Else

Print"NOTOK!"

EndIf

33、怎么用QTP随机获得键盘的输入值,主要是字符,数字,标点符号,常用符号等

MsgboxGetRandomChar2

FunctionGetRandomChar()

DimStrArray

StrArray=Array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")

Randomize

ub=Ubound(StrArray)

idx=Int((ub-0+1)*Rnd+0)

GetRandomChar=StrArray(idx)

EndFunction

FunctionGetRandomChar2()

Randomize

idx=Int((ub-32+126)*Rnd+32)

GetRandomChar2=Chr(idx)

'ForI=32to126

'PrintI&":"&Chr(I)

'Next

EndFunction

34、如何判断ToolbarWindow32下的按钮变灰不可用呢

如何判断ToolbarWindow32下的按钮变灰不可用呢

IfWindow("XXX").WinToolbar("XXX").GetItemProperty(1,"enabled")=FalseThen

...

Else

...

EndIF

35、如何产生6个不重复的随机数?

Dimnum,A(6),Redvalue

Randomize

num=0

Redvalue=0

Whilenum<6

newnum=Int(20*Rnd+1)

iR=False

ForI=0Tonum

IFA(I)=newnumThen

iR=True

EndIF

Next

IfiR=FalseThen

A(num)=newnum

num=num+1

EndIf

Wend

MsgboxA(0)&""&A(1)&""&A(2)&""&A(3)&""&A(4)&""&A(5)

36、如何使用HTMLDOM进行自动化测试?

测试Google的小例子:

DimoIee,objedit

DimoPagtxt

SetoIee=CreateObject("InternetExplorer.Application")

oIee.navigate("http://www.google.com.hk")

oIee.Visible=True

DoWhileoIee.readystate<>4

Loop

SetoPagtxt=oIee.document

setobjedit=oPagtxt.getelementsbyname("q")

objedit(0).value="QTP自动化测试进阶"

setobjbutton=oPagtxt.getelementsbyname("btnG")

objbutton(0).Click

SetoIee=Nothing

37、为什么QTP录制了网页的后退功能后,回放时运行出错?

Browser().Back是可以后退的,可能你的浏览器重置过

工具->Internet选项->程序->管理加载项,选择“InternetExplorer已经使用的加载项”,查找“BHOManagerClass”,在下面的“设置”中选择“启用”,重启IE就可以了。

用模拟键盘方式控制浏览器后退:

Browser("百度一下,你就知道").Page("百度一下,你就知道").WebEdit("wd").Set"QTP"

Browser("百度一下,你就知道").Page("百度一下,你就知道").WebButton("百度一下").Click

'Browser("百度一下,你就知道").Back

Wait3

SetWshShell=CreateObject("WScript.Shell")

WshShell.SendKeys"%({LEFT})"

SetWshShell=Nothing

38、如何随机获得一个任意长度的字符串,主要是包含字母,数字,标点符号,常用符号等

MsgboxGetRandomChars(10)

FunctionGetRandomChars(length)

Dimstr

ForI=0tolength

Randomize

idx=Int((ub-32+126)*Rnd+32)

str=str&Chr(idx)

Next

GetRandomChars=str

EndFunction

39、WinMenu如何获取所有菜单项?

Setobj_Menu=VbWindow("frm_main").WinMenu("Menu")

GetNamesRec"",obj_Menu

'OpenAllMenusandSub-MenusandWritetheMenuNamesintheResults

FunctionGetNamesRec(itemPath,menuObj)

ret=0

lbl=menuObj.GetItemProperty(itemPath,"Label")

Reporter.ReportEvent0,itemPath&"label",lbl

ret=menuObj.GetItemProperty(itemPath,"HasSubMenu")

IfretThen

cnt=menuObj.GetItemProperty(itemPath,"SubMenuCount")

Reporter.ReportEvent0,itemPath&"sub-menuitems",cnt

Forn=1Tocnt

Path=menuObj.BuildMenuPath(itemPath,n)

GetNamesRecPath,menuObj

Next

EndIf

EndFunction

40、WinMenu如何检查某个菜单项是否存在?

IfVbWindow("frm_main").WinMenu("Menu").CheckItemProperty("File;Open","Exists",True,1000)<>TrueThen

Reporter.ReportEventmicPass,"找不到指定菜单项","找不到"&Menu

Else

‘…

EndIf

41、如何获取两个时间的差?

dimtime1,time2,time3

time1=TimeValue("17:32:44")

time2=TimeValue("17:32:51")

MsgboxDateDiff("s",time1,time2)

42、QTP不支持WPS的XLS文件?

DataTable.ImportSheet"D:\XX-Project\data\Flight.xls","Resource","Global"

报错:

TheDataTable.ImportSheetoperationfailed.FilecontainsafeaturenotsupportedbyFormulaOne.

QTP也不支持太高版本的Office,例如2007,即使用Office2007另存为2003格式也不支持。

43、sql语句中动态变量中间含有单引号,查询出错

dimx

x=DataTable("title","add")'将数据表中title列的当前值取出

dimconn,rst

中间为数据库连接语句。此处省略了

rst.open“select*fromnavigatewherename=‘“&x&”’”,conn'此处为方便查看,将单引双引号用中文状态下书写

在x变量为正常字符串时,都可以成功查询。但当x为含有单引号的字符串,例如“i'think”。系统会报错,说语法存在问题。

"select*fromnavigatewherename="&Chr(39)&x&Chr(39)

or

rst.open"select*fromnavigatewherename='"&replace(x,"'","''")&"'"

44、vbs中处理日期格式

例如date返回的是2010-8-20日,现在我想要08-20-2010

msgboxDatePart("m",date)&"-"&DatePart("d",date)&"-"&DatePart("yyyy",date)

45、QTP目录中MSR.fbr文件能否删除?

MSR.fbr是运行过程中屏幕录像文件,如果不需要,可以删除。或者也取消生成MSR.fbr,在QTP-Tools-Options-Run中,取消勾选SaveMovietoresults(QTP9.2)

46、如何在QTP中利用HTTP请求-响应来检查WEB页面链接?

  '===================================================================

  'Name:CheckAllLinkReachable

  'Summary:CheckAllLinkReachable

  'Parameters:

  'strBrowser:browsername

  'strPage:pagename

  'strURLPattern:URLpatternyouwan'ttocheck.suchas:^http.*

  'Return:None

  '===================================================================

  FunctionCheckAllLinkReachable(strBrowser,strPage,strURLPattern)

  DimblnReachable

  blnReachable=True

  SetobjXML=CreateObject("Msxml2.XMLHTTP")

  'Getalllinkonthepage

  SetobjDes=Description.Create

  objDes("micclass").Value="Link"

  SetobjLinkList=Browser(strBrowser).Page(strPage).ChildObjects(objDes)

  Fori=0ToobjLinkList.Count()-1

  'CreateXMLHTTPObject

  strURL=objLinkList(i).GetROProperty("href")

  IfRegExpTest(strURLPattern,strURL)Then

  objXML.Open"POST",strURL,false

  objXML.Send

  'msgboxobjXML.responseText

  print(objLinkList(i).GetROProperty("href")&"ReadyState:"&objXML.readyState&"Status:"&objXML.status)

  IfobjXML.status<>"200"Then

  blnReachable=False

  EndIf

  objXML.abort()

  EndIf

  Next

  SetobjXML=Nothing

  CheckAllLinkReachable=blnReachable

  EndFunction

47、如何在QTP中压缩文件?

CallfZip("D:\testZip","D:\testZip.zip")

CallfUnzip("D:\testZip.zip","D:\testUnZip")

FunctionfZip(sSourceFolder,sTargetZIPFile)

'ThisfunctionwilladdallofthefilesinasourcefoldertoaZIPfile

'usingWindows'nativefolderZIPcapability.

'Returnsaninteger0ifeverythingwentok.

DimoShellApp,oFSO,iErr,sErrSource,sErrDescription

SetoShellApp=CreateObject("Shell.Application")

SetoFSO=CreateObject("Scripting.FileSystemObject")

'Thesourcefolderneedstohavea\ontheEnd

IfRight(sSourceFolder,1)<>"\"ThensSourceFolder=sSourceFolder&"\"

OnErrorResumeNext

'IfatargetZIPexistsalready,deleteit

IfoFSO.FileExists(sTargetZIPFile)ThenoFSO.DeleteFilesTargetZIPFile,True

iErr=Err.Number

OnErrorGoTo0

IfiErr<>0Then

fZip=iErr

ExitFunction

EndIf

OnErrorResumeNext

'Writethefileheaderforablankzipfile.

oFSO.OpenTextFile(sTargetZIPFile,2,True).Write"PK"&Chr(5)&Chr(6)&String(18,Chr(0))

iErr=Err.Number

OnErrorGoTo0

IfiErr<>0Then

fZip=iErr

ExitFunction

EndIf

OnErrorResumeNext

'Startcopyingfilesintothezipfromthesourcefolder.

oShellApp.NameSpace(sTargetZIPFile).CopyHereoShellApp.NameSpace(sSourceFolder).Items

iErr=Err.Number

OnErrorGoTo0

IfiErr<>0Then

fZip=iErr

ExitFunction

EndIf

'Becausethecopyingoccursinaseparateprocess,thescriptwilljustcontinue.RunaDO...LOOPtopreventthefunction

'fromexitinguntilthefileisfinishedzipping.

DoUntiloShellApp.NameSpace(sTargetZIPFile).Items.Count=oShellApp.NameSpace(sSourceFolder).Items.Count

'WScript.Sleep500

Wait1

Loop

fZip=0

EndFunction

FunctionfUnzip(sZipFile,sTargetFolder)

'CreatetheShell.Applicationobject

DimoShellApp:SetoShellApp=CreateObject("Shell.Application")

'CreatetheFileSystemobject

DimoFSO:SetoFSO=CreateObject("Scripting.FileSystemObject")

'Createthetargetfolderifitisn'talreadythere

IfNotoFSO.FolderExists(sTargetFolder)ThenoFSO.CreateFoldersTargetFolder

'Extractthefilesfromthezipintothefolder

oShellApp.NameSpace(sTargetFolder).CopyHereoShellApp.NameSpace(sZipFile).Items

'Thisisaseperateprocess,sothescriptwouldcontinueeveniftheunzippingisnotdone

'Topreventthis,werunaDO...LOOPonceasecondcheckingtoseeifthenumberoffiles

'inthetargetfolderequalsthenumberoffilesinthezipfile.Ifso,wecontinue.

Do

'WScript.Sleep1000

Wait1

LoopWhileoFSO.GetFolder(sTargetFolder).Files.Count<oShellApp.NameSpace(sZipFile).Items.Count

EndFunction

48、SomeusefultipofQTP

SharingsometipaboutQTPwheniuseQTPinmytwork!ihopethesecanbeuseful,IurgethereaderstosharetheirexperiencesortipstheyhaveusedwhileworkingonQTP.

1)howtoaddconstantnumbertodatatableinQTP?

ThisismoretodowithMSexcelthenQTP!!ifyouwanttoenternumberof1234567todatatable,youcanwriteitas'1234567.Justappendsinglequotesbeforethenumber.

2)howcanicheckckeckpointpassornot?

youcandoso!

chk_PassFail=Browser(...).Page(...).WebEdit(...).Check(Checkpoint("Check1"))

ifchk_PassFailthen

MsgBox"CheckPointpassed"

elseMsgBox"CheckPointfailed"

endif

3)WhentouseaRecoveryScenarioandwhentouseonerrorresumenext?

RecoveryScenarioisusedwhenyoucannotpredictatwhatstep(s)theerrorcanbeocurred,"Onerrorresumenext"shouldbeusedwhenyouknowifanerrorisexpectedanddontwanttoraiseit,youmaywanttohavedifferentactionsdependingupontheerror
thatoccurred.Useerr.number&err.descriptiontogetmoredetailsabouttheerror.

4)whattodoifyoucannotrunQTPfromQC?

Thisisforespeciallyfornewbie!

checkthatyouhavebeenticked"Allowothermercuryproductstoruntestsandcomponents"fromTools-->Options-->RunTab.

49、如何取到某个目录下的所以文件?

Setfso=CreateObject("Scripting.FileSystemObject")

Setf=fso.GetFolder("C:\")

Setfc=f.Files

ForEachf1infc

Printf1.name

Next

50、如何检查是否ping通网络?

FunctionzGen_Ping(sHost)

'Thisfunctionchecksthatyoucangetthroughtothehostyourequire

'Exampleusage:

''Checkwehaveinternet...

'IfNotzGen_Ping("www.google.com")Then

'Msgbox"NotconnectedtoInternet",vbCritical,"FatalError:"

'CallExitTest()

'EndIf

Print"Gen_Ping:"&sHost

DimoPing,oRetStatus

SetoPing=GetObject("winmgmts:").ExecQuery("select*fromWin32_PingStatuswhereaddress='"&sHost&"'")

ForEachoRetStatusInoPing

IfIsNull(oRetStatus.StatusCode)OroRetStatus.StatusCode<>0Then

Print"Gen_PingFailed-Statuscode:"&oRetStatus.StatusCode

zGen_Ping=False

Else

Print"Gen_PingOK-Bytes:"&vbTab&oRetStatus.BufferSize

Print"Gen_PingOK-Time(ms):"&vbTab&oRetStatus.ResponseTime

Print"Gen_PingOK-TTL(s):"&vbTab&oRetStatus.ResponseTimeToLive

zGen_Ping=True

EndIf

Next

SetoPing=Nothing

EndFunction

51、IE8脚本错误提示脚本导致浏览器运行慢的解决办法

1.UsingaRegistryEditorsuchasRegedt32.exe,openthiskey:HKEY_CURRENT_USER\Software\Microsoft\InternetExplorer\Styles

Note:IftheStyleskeyisnotpresent,createanewkeythatiscalledStyles.

2.CreateanewDWORDvaluecalled“MaxScriptStatements”underthiskeyandsetthevaluetothedesirednumberofscriptstatements.Ifyouareunsureofwhatvalueyouneedtosetthisto,youcansetittoaDWORDvalueof0xFFFFFFFFtocompletelyavoid
thedialog.

SubIE_ChangeScriptTimeOut()

DimRegistry,sKeyPath,sValueName,dwValue,sComputer

CONSTHKEY_CURRENT_USER=&H80000001


sKeyPath="Software\Microsoft\InternetExplorer\Styles"

sValueName="MaxScriptStatements"

dwValue=-1

sComputer="."


OnErrorResumeNext

SetRegistry=GetObject("winmgmts:{impersonationLevel=impersonate}!\\"&_

sComputer&"\root\default:StdRegProv")


Registry.CreateKeyHKEY_CURRENT_USER,sKeyPath

Registry.SetDWORDValueHKEY_CURRENT_USER,sKeyPath,sValueName,CLng(dwValue)

OnErrorGoto0


SetRegistry=Nothing

EndSub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: