(转)TIB自动化测试工作室-QTP脚本汇总比较有价值

上一篇 / 下一篇  2016-06-13 15:19:13 / 个人分类:UFT11.5

 

http://www.cnblogs.com/testware

 

 

1、Object Spy的Tips

Hold the CTRL key to change the window focus or perform. other mouse operations

 

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

安装Microsoft Script. Debuger即可

 

3、QTP如何访问Oracle数据库

Dim rs,sq,pkey
set conn=createobject("adodb.connection")
set rs=createobject("adodb.recordset")

' 需要安装Oracle客户端
conn.open "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;User ID=scott;Data Source=orcl;Password=orcl;Extended Properties=;Host=192.168.1.188;Port=1521;Service Name=orcl;" 

sql="SELECT * FROM TAB"
rs.open sql,conn
rs.MoveFirst
Do While rs.Eof<>true
Msgbox rs.Fields(0)
rs.MoveNext
Loop
rs.close
set rs=nothing
conn.close
set conn=nothing

 

 

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

Dim oWebChkDesc

Set WebChkDesc = Description.Create

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

oWebChkDesc("html tag").Value = "INPUT"

 

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

Dim allCheck, oCheckBox

Set allCheck = Browser("Web Tours").Page("Web Tours").ChildObjects(oWebChkDesc)

For i = 0 to allCheck.Count - 1

       Set CheckBox = allCheck(i)

       oCheckBox.Set "ON"

Next

 

 

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

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

Microsoft Internet Explorer 6.0 Service Pack 1

Microsoft Internet Explorer 7.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 -> View Options

 

 

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

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

 

 

 

Dim qtApp 'As QuickTest.Application ' Declare the Application object variable

Dim qtTest 'As QuickTest.Test ' Declare a Test object variable

Dim qtResultsOpt 'As QuickTest.RunResultsOptions ' Declare a Run Results Options object variable

 

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object

qtApp.Launch ' Start QuickTest

qtApp.Visible = True ' Make the QuickTest application visible

 

' Set QuickTest run options

qtApp.Options.Run.ImageCaptureForTestResults = "OnError"

 

qtApp.Options.Run.RunMode = "Fast"

qtApp.Options.Run.ViewResults = False

 

qtApp.Open "C:\Tests\Test1", True ' Open the test in read-only mode

 

' set run settings for the test

Set qtTest = qtApp.Test

qtTest.Settings.Run.IterationMode = "rngIterations" ' Run only iterations 2 to 4

qtTest.Settings.Run.StartIteration = 2

qtTest.Settings.Run.EndIteration = 4

qtTest.Settings.Run.OnError = "NextStep" ' Instruct QuickTest to perform. next step when error occurs

 

Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object

qtResultsOpt.ResultsLocation = "C:\Tests\Test1\Res1" ' Set the results location

 

qtTest.Run qtResultsOpt ' Run the test

 

MsgBox qtTest.LastRunResults.Status ' Check the results of the test run

qtTest.Close ' Close the test

 

Set qtResultsOpt = Nothing ' Release the Run Results Options object

Set qtTest = Nothing ' Release the Test object

Set qtApp = Nothing ' Release the Application object

 

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

 

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

 

 

10、QTP支持的正则表达式

 

 

使用反斜杠字符 ( \ )

匹配任意单个字符 ( . )

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

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

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

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

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

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

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

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

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

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

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

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

 

 

 

 

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

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

 

 

SystemUtil.CloseProcessByName "excel.exe"

 

On error resume next

  Dim Obj

  Set bj = GetObject(,"Excel.Application")

  If Not Obj Is Nothing Then      

  Obj.Quit     

  Set bj = Nothing

End If

 

或者:

' To kill excel application

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

 

'To check if excel is running use this function

msgbox "Excel is Running:" & FindProcess("EXCEL.EXE")

 

Function FindProcess(ByVal ProcessName)

  FindProcess= False   

  Set Shell = CreateObject("WScript.Shell")       

  Set ShellResult = Shell.Exec("TaskList")         

  While Not ShellResult.StdOut.AtEndOfStream         

    If Instr(UCASE(ShellResult.StdOut.ReadLine),UCASE(ProcessName)) Then

      FindProcess = True                

      Exit Function              

    End If         

  Wend  

End Function

 

 

 

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

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

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

 

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

 

' Disable the Firewall

 

Set bjFirewall = CreateObject("HNetCfg.FwMgr")

Set bjPolicy = objFirewall.LocalPolicy.CurrentProfile

 

objPolicy.FirewallEnabled = FALSE

 

Set bjPolicy = Nothing

Set bjFirewall = Nothing

 

 

 

 

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

 

   Dim fso, msg,fldr

   fldr = "D:\books"

   Set fso = CreateObject("Scripting.FileSystemObject")

   If (fso.FolderExists(fldr)) Then

      msg = fldr & " exists."

   Else

      msg = fldr & " doesn't exist."

   End If

   Msgbox msg

 

 

 

15、QTP菜单丢失的问题

 

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

 

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

 

 

 

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

 

Dim WshShell, bKey

Set WshShell = CreateObject("WScript.Shell")

ON Error Resume Next

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

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

If bKey = vbEmpty Then

       Msgbox "Key Not Exists!"

End IF

Set WshShell=Nothing

 

 

 

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

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

 

 

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

 

附JMail接收邮件的脚本:

Set pop3 = CreateObject("JMail.POP3")

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

 

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

Set msg = pop3.Messages.Item(1)

Print msg.Subject

Print msg.FromName

Print msg.Body

 

Set pop3 = Nothing

 

 

 

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

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

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

 

 

Set bjWsh = CreateObject("Wscript.shell")

'压缩

objWsh.Run "winrar a D:\test\test.rar D:\test\*.txt",0,True

'解压缩

objWsh.Run "winrar x -o+ D:\test\test.rar *.txt D:\test\",0,True

Set bjWsh = Nothing

 

 

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

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

 

Const   ssfCONTROLS   =   3  

   

  sConnectionName   =   "无线网络连接"  

   

  sEnableVerb   =   "启用(&A)"  

  sDisableVerb   =   "停用(&B)"  

   

  set   shellApp   =   createobject("shell.application")  

  set   oControlPanel   =   shellApp.Namespace(ssfCONTROLS)  

   

  set   oNetConnections   =   nothing  

  for   each   folderitem   in   oControlPanel.items  

    if   folderitem.name     =   "网络连接"   then  

        set   oNetConnections   =   folderitem.getfolder:   exit   for  

    end   if  

  next  

   

  if   oNetConnections   is   nothing   then  

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

    wscript.quit  

  end   if  

   

  set   oLanConnection   =   nothing  

  for   each   folderitem   in   oNetConnections.items  

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

        set   oLanConnection   =   folderitem:   exit   for  

    end   if  

  next  

   

  if   oLanConnection   is   nothing   then  

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

    wscript.quit  

  end   if  

   

  bEnabled   =   true  

  set   oEnableVerb   =   nothing  

  set   oDisableVerb   =   nothing  

  s   =   "Verbs:   "   &   vbcrlf  

  for   each   verb   in   oLanConnection.verbs  

    s   =   s   &   vbcrlf   &   verb.name  

    if   verb.name   =   sEnableVerb   then    

        set   oEnableVerb   =   verb      

        bEnabled   =   false  

    end   if  

    if   verb.name   =   sDisableVerb   then    

        set   oDisableVerb   =   verb      

    end   if  

  next  

   

  'debugging   displays   left   just   in   case...  

  '  

  'msgbox   s   ':   wscript.quit  

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

   

  'not   sure   why,   but   invokeverb   always   seemed   to   work    

  'for   enable   but   not   disable.      

  '  

  'saving   a   reference   to   the   appropriate   verb   object    

  'and   calling   the   DoIt   method   always   seems   to   work.  

  '  

  if   bEnabled   then  

  '     oLanConnection.invokeverb   sDisableVerb  

    oDisableVerb.DoIt  

  else  

  '     oLanConnection.invokeverb   sEnableVerb  

    oEnableVerb.DoIt  

  end   if  

   

  'adjust   the   sleep   duration   below   as   needed...  

  '  

  'if   you   let   the   oLanConnection   go   out   of   scope  

  'and   be   destroyed   too   soon,   the   action   of   the   verb  

  'may   not   take...  

  '  

wscript.sleep   400 

 

20、QTP怎么检测XML文档?

(1)使用XMLUtil对象。

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

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

Set doc = XMLUtil.CreateXML()

' 加载XML文件用于检查

doc.LoadFile "Test.XML"

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

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

ans = doc.Validate ("D:\Program Files\Mercury Interactive\QuickTest Professional\dat\ObjectRepository.xsd")

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

If ans Then

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

else

       errNo = doc.GetValidationErrorsNumber

        For i = 1 to errNo

              errStr = doc.GetValidationError(i)

              MsgBox errStr

       Next

End If

 

 

 

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

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

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

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

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

xmlDoc.async = False  

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

' 检查XML文档是否有错误

If xmlDoc.parseError.errorCode <> 0 Then  

   Set myErr = xmlDoc.parseError

   MsgBox("XML Loads Failed. " & myErr.reason)

Else

        Set rootNode = xmlDoc.documentElement

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

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

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

 

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

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

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

           xmlDoc.save "test_save.xml"

End If

Set xmlDoc = Nothing

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

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

 

这是对象动态 变化了

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

Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("add to cart").Click

Wait 2

Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("check_cart_icon").Click

 

也可以这样:

Do until Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("check_cart_icon").Exist(2)

Loop

 

 

 

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

 

提示错误:

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

 

I have a problem in connecing QTP to DB2 and fetch query results.

 

My script. goes like this: (sample POC)

 

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

 

msgbox db_connect (curSession, connection_string)

 

Function db_connect( byRef curSession ,connection_string)

dim connection

on error Resume next

' Opening connection

set connection = CreateObject("ADODB.Connection")

If Err.Number <> 0 then

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

err.clear

Exit Function

End If

 

connection.Open connection_string

If Err.Number <> 0 then

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

err.clear

Exit Function

End If

 

set curSession=connection

db_connect=0

 

End Function

 

This script. is popping up this error msg:

 

[IBM][CLI Driver] SQL1042C An unexpected system error occurred. SQLSTATE=58004

 

For the other connection string type,

 

data_DSN = "QAProd" 'dsn created in control panel

data_usr = "admin"

data_pwd = "adminqa"

data_alias = "ecomdb" 'name of the database

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

 

i am getting same error or another error saying

 

password error - not able to reproduce when posting this thread

 

I checked connectionstrings.com and other threads in this forum discussing about QTP-DB2 connection, but couldn't find out the answer for my problem.

 

help me to untie this problem.

 

TAG:

 

评分:0

我来说两句

日历

« 2024-05-15  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 8420
  • 日志数: 15
  • 建立时间: 2016-06-13
  • 更新时间: 2016-07-29

RSS订阅

Open Toolbar