共同探讨QTP相关问题

发布新日志

  • HTML DOM学习心得(附:开心网查找空车位函数)

    2008-12-28 14:30:29

    HTML Dom是一个访问HTML文档的W3C标准。它定义了如何去访问页面元素对象以及属性和方法。
    在DOM标准里面:
    1 整个HTML文档是一个文档节点。
    2 每一个HTML 标签都是一个元素节点。
    3 HTML 文本都是文本节点。
    4 每一个HTML 属性都是一个属性节点。

    HTML DOM 的一些主要属性(x是一个HTEML元素)
    x.innerHtml - the inner text value of x (a HTML element)
    x.nodeName - the name of x
    x.nodeValue - the value of x
    x.parentNode - the parent node of x
    x.childNodes - the child nodes of x
    x.attributes - the attributes nodes of x

    HTML DOM 的一些主要方法(x是一个HTEML元素)
    x.getElementById(id) - get the element with a specified id
    x.getElementsByTagName(name) - get all elements with a specified tag name
    x.appendChild(node) - insert a child node to x
    x.removeChild(node) - remove a child node from x

    通常访问HTML DOM节点有一下三种方法:
    1 使用getElementById()
      node.getElementsByTagName("tagname");
    2 使用getElementsByTagName()
      x=document.getElementsByTagName("p");
      For i = 0 to x.Length - 1
        Print x(i).innerText
    3 使用HTML文档的节点树导航
      node.firstChild
      node.childNodes
      node.parentNode

    掌握HTML DOM对qtp web测试是很有帮助的。
    下面有个简单的例子,在开心网上搜索好友列表并把相应的车位状态取出来。如果用qtp实现的话有下面几个难点,好友的列表的长度是动态变化的,好友名称是不固定的,不同的登陆用户有不同的好友。
    使用HTML DOM就可以比较方便的解决找个问题,查看页面源代码我们知道每一个好友都是存在一个"UL"标签里面,而好友的车位状态是存在"LI"标签的子节点里面。

    Function Find_Park()
    Dim d
    Set d = createobject("scrīpting.dictionary")

    'Get all the "UL" tag from the page, each object contains the information of one friend
    Set friends = Browser("争车位 - 开心网").Page("争车位 - 开心网").Object.getElementsByTagName("ul")
    For i = 0 to friends.Length - 1
     'Get all the "LI" tag within each friend, one object  whose style is "FLOAT: right" contain the status of the park
     Set friendAttrs = friends(i).GetElementsByTagName("li")

     blnFlag = False
     For j = 0 to friendAttrs.Length - 1
      If strComp("FLOAT: right", friendAttrs(j).style.csstext, 1) = 0 Then
       Set imgs =  friendAttrs(j).GetElementsByTagName("img")
       d.Add friends(i).InnerText, imgs(0).GetAttribute("alt")
       blnFlag = True
       Exit For
      End If
     Next

     If Not blnFlag Then
      d.Add friends(i).InnerText, "空"
     End If
    Next

    Set Find_Park = d
    End Function

  • 如何使用qtp操作OpenOffice

    2008-11-17 20:59:26

    Public Function ConvertToURL(cFilename)
    Dim sURL
    ' Ensure leading slash.
    If Left(cFilename, 1) <> "/" Then
    cFilename = "/" + cFilename
    End If
    sURL = Replace(cFilename, "\", "/") 'change backslashes to forward slashes.
    sURL = "file://" + sURL 'Example: "
    file:///E:/Sample Files/Sample.ods"
    ConvertToURL = sURL
    End Function


     

    Function GetData(sFileName, sSheetName)
    Dim objServiceManager
    Dim oDesktop
    Dim oDocument
    Dim oSheet
    Dim oParCursor
    Dim oCell
    Dim xSearchDesc

    Set ōbjServiceManager = CreateObject("com.sun.star.ServiceManager")
    Set ōDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop")
    Set ōDocument = oDesktop.loadComponentFromURL(ConvertToURL(sFileName), "_blank", 0, Array())
    Set ōSheet = oDocument.Sheets.getByName(sSheetName)

    Set xSearchDesc = oSheet.createSearchDescrīptor()
    xSearchDesc.SetSearchString("DC")
    Set ōCell = oSheet.findFirst(xSearchDesc)
    MsgBox oCell.getCellAddress().Row
    MsgBox oCell.getCellAddress().Column '//Use the openoffice search function to getcell and return the row and column

    Set ōRowCursor = oSheet.createCursor()
    oRowCursor.gotoStartofUsedArea(false)
    oRowCursor.gotoEndofUsedArea(True)
    MsgBox oRowCursor.getrows.Count


    Set ōColumnCursor = oSheet.createCursor()
    oColumnCursor.gotoStartofUsedArea(false)
    oColumnCursor.gotoEndofUsedArea(True)
    MsgBox oColumnCursor.getColumns.Count

    MsgBox oSheet.GetCellByPosition(0, 0).GetString()

    End Function

  • 如何根据对象名找出对象库中完整路径的对象

    2008-11-06 01:01:28

    Dim MyArray()
    Dim RowNumber
    RowNumber = 100
    ReDim MyArray(2, RowNumber)
    Dim RowCount
    Set RootObj = CreateObject("Mercury.ObjectRepositoryUtil") 
    RootObj.Load "E:\Project\QTPTest\test.tsr" 
    RowCount = 0
    EnumberateRepository(NULL)

    If RowCount < UBound(MyArray, 2) Then
     ReDim Preserve MyArray(2, RowCount-1)
    End If

    Execute GetobjectDescrīption("q")&".Set "&"""Randall"""
    Set RootObj = Nothing
    '***************************************************************************************
    Sub EnumberateRepository(Root)
        Dim TOCollection, TestObject, PropertiesCollection
        Set TOCollection = RootObj.GetChildren(Root)
     If RowCount > Ubound(MyArray, 2) Then
      ReDim Preserve MyArray(2, Ubound(MyArray, 2) + 100)
     End If
        For i = 0 To TOCollection.Count - 1
                Set TestObject = TOCollection.Item(i)
       MyArray(0, RowCount) = TestObject.GetToProperty("MicClass")
       MyArray(1, RowCount) = RootObj.GetLogicalName(TestObject)
       If IsNull(Root) Then
        MyArray(2, RowCount) = ""
       Else  
        MyArray(2, RowCount) = RootObj.GetLogicalName(Root)
       End If   
      RowCount = RowCount +1
         EnumberateRepository TestObject  
         Next 
    End Sub
    '***************************************************************************************
    Function GetobjectDescrīption(objname)
    Dim ObjDescrīption, ParentName
    ObjDescrīption = ""
    i = UBound(MyArray, 2)
    ParentName = objname
    While i >= 0
    If StrComp(myarray(1, i), ParentName) = 0 Then
        ParentName = myarray(2, i)
        If StrComp(ObjDescrīption, "") = 0 then
        ōbjDescrīption = MyArray(0, i)&"("&chr(34)&MyArray(1, i)&chr(34)&")"
        Else
        ōbjDescrīption = MyArray(0, i)&"("&chr(34)&MyArray(1, i)&chr(34)&")"&"."&ObjDescrīption
     End If
     If StrComp(myarray(2, i), "") = 0 Then
     GetobjectDescrīption = ObjDescrīption
     Exit Function
     End If 
    End If 
    i = i - 1
    Wend
    End Function
  • DataTable使用方法

    2008-08-08 22:25:57

    Function ImportSheet(ExcelSheetName)
       Err.Clear
       Dim sheetCount
       sheetCount = DataTable.GetSheetCount
       For i = 1 to sheetCount
        If strcomp(ExcelSheetName, DataTable.GetSheet(i).Name) = 0 Then
         ImportSheet = True
         Exit Function
        End If
       Next
       DataTable.AddSheet ExcelSheetName
       DataTable.ImportSheet "RandallTest.xls", ExcelSheetName, ExcelSheetName
       If Err.Number<>0 Then
        ImportSheet = False
        Exit Function
       Else
          ImportSheet = True   
       End If
    End Function

    Function GetCellData(DTSheetName, FieldName, Row)
       Err.Clear
       Dim sheetCount
       Dim blnExist
       blnExist = False
       sheetCount = DataTable.GetSheetCount
       For i = 1 to sheetCount
        If strcomp(DTSheetName, DataTable.GetSheet(i).Name) = 0 Then
         blnExist = True
         Reporter.ReportEvent micDone, "GetSheet: "+DTSheetName, "Passed"
         Exit For
        End If
       Next  
       If Not blnExist Then
        Reporter.ReportEvent micFail, "Sheet Exist: "+ DTSheetName, "Failed"
        GetCellData = False
        Exit Function
       End If
       DataTable.SetCurrentRow Row
       GetCellData = DataTable.Value(FieldName, DTSheetName)
       If Err.Number<>0 Then
        Reporter.ReportEvent micFail, "GetSheetValue", "Failed"
        Exit Function
       End If
    End Function

  • Excel 操作

    2008-08-02 11:53:25

     Excel.Application

    Excel中几个常用对象:WorkBooks,WorkSheets,Cells.可以通过Name属性标识,也可通过index标识。

     Dim ExcelApp
     Set ExcelApp = CreateObject("Excel.Application")
     ExcelApp.WorkBooks.Open "F:\RandallTest.xls"
     Dim myWorkBook
     Set myWorkBook = ExcelApp.workbooks(1)
     myWorkBook.WorkSheets("Sheet1").Activate
     Dim myWorkSheet
     Set myWorkSheet = myWorkBook.worksheets("Sheet1")
     msgbox myWorkSheet.Cells(1,1).Value
     myWorkSheet.Cells(1,1).Value = "temp"
     myWorkBook.SaveAs "C:\RandallTest.xls"
     Set ExcelApp = nothing

  • 使用Object Repository Automation Objects and Methods操作对象库

    2008-07-13 11:39:58

    Dim RepositoryFrom,TOCollection
    Set RepositoryFrom = CreateObject("Mercury.ObjectRepositoryUtil")
    RepositoryFrom.Load "C:\Login.tsr"
    Set TOCollection = RepositoryFrom.GetAllObjectsByClass("WinButton")
    Msgbox TOCollection.Count

    具体可参照help文档中关于ObjectRepositoryUtil的应用.

    'The following example retrieves an object repository's objects and properties,

    'looks for specific test objects using several methods, and copies a test object
    'to another object repository.
    Dim ImageObj, PageObj, RepositoryFrom, RepositoryTo
    Set RepositoryFrom = CreateObject("Mercury.ObjectRepositoryUtil")
    Set RepositoryTo = CreateObject("Mercury.ObjectRepositoryUtil")
    RepositoryFrom.Load "C:\QuickTest\Tests\Flights.tsr"
    RepositoryTo.Load "E:\Temp\Tests\Default.tsr"


     

    Function EnumerateAllChildProperties(Root)
    'The following function recursively enumerates all the test objects directly under
    'a specified parent object. For each test object, a message box opens containing the
    'test object's name, properties, and property values.
        Dim TOCollection, TestObject, PropertiesCollection, Property, Msg
        Set TOCollection = RepositoryFrom.GetChildren(Root)
        For i = 0 To TOCollection.Count - 1
                Set TestObject = TOCollection.Item(i)
                Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine
                Set PropertiesCollection = TestObject.GetTOProperties()
                For n = 0 To PropertiesCollection.Count - 1
                    Set Property = PropertiesCollection.Item(n)
                    Msg = Msg & Property.Name & "-" & Property.Value & vbNewLine
                Next
                MsgBox Msg
    EnumerateAllChildProperties TestObject
        Next
    End Function


     

    Function EnumerateAllObjectsProperties(Root)
    'The following function enumerates all the test objects under a specified object.
    'For each test object, a message box opens containing the test object's name,
    'properties, and property values.
     Dim TOCollection, TestObject, PropertiesCollection, Property, Msg
        Set TOCollection = RepositoryFrom.GetAllObjects(Root)
        For i = 0 To TOCollection.Count - 1
            Set TestObject = TOCollection.Item(i)
                        Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine
                Set PropertiesCollection = TestObject.GetTOProperties()
                For n = 0 To PropertiesCollection.Count - 1
                    Set Property = PropertiesCollection.Item(n)
                    Msg = Property.Name & "-" & Property.Value & vbNewLine
                Next
            MsgBox Msg
        Next
    End Function


     

    Function RenameAllImages(Root)
    'The following function sets a new name for all image test objects under a specified object.
     Dim TOCollection, TestObject, PropertiesCollection, Property
        Set TOCollection = RepositoryTo.GetAllObjectsByClass("Image")
        For i = 0 To TOCollection.Count - 1
                Set TestObject = TOCollection.Item(i)
                RepositoryTo.RenameObject (TestObject, "Image " & i)
                RepositoryTo.UpdateObject TestObject
        Next
    End Function


     

    Function RemoveAllLinks(Root)
    'The following function recursively enumerates all the test objects under a specified object.
    'It looks for all test objects of class Link and removes them from their parent objects.
        Dim TOCollection, TestObject, PropertiesCollection, Property
        Set TOCollection = RepositoryFrom.GetChildren(Root)
        For i = 0 To TOCollection.Count - 1
                Set TestObject = TOCollection.Item(i)
                TOClass = TestObject.GetTOProperty("micclass")
             If TOClass = "Link" Then
                    RepositoryFrom.RemoveObject Root, TestObject
                End If
            EnumerateAllChildProperties TestObject
        Next
    End Function


     

    Call EnumerateAllChildProperties(Null)
    Call EnumerateAllObjectsProperties(Null)
    Call RenameAllImages(Null)
    Call RemoveAllLinks(Null)
    Set ImageObj = RepositoryFrom.GetObject("Browser(""CNN.com"").Page(""CNN.com"").Image(""Remains identified"")")
    If (Not IsNull(ImageObj)) Then
     MsgBox RepositoryFrom.GetLogicalName(ImageObj)
     Else MsgBox "null"
    End If
    Set PageObj = RepositoryTo.GetObjectByParent("Browser(""CNN.com"")", "Page(""CNN.com"")")
    If (Not IsNull(PageObj)) Then
     MsgBox RepositoryTo.GetLogicalName(PageObj)
     Else MsgBox "null"
    End If
    RepositoryTo.AddObject ImageObj, PageObj
    RepositoryFrom.Save
    RepositoryTo.Save
  • VBS 常用数据库函数

    2008-06-21 14:28:41

    VBS写的常用数据库公用函数

    摘自http://bbs.51testing.com/viewthread.php?tid=118028&pid=998989&page=1&extra=page%3D1#pid998989
    以下是我写的常用的数据库公用函数,希望大家能一起探讨和总结,把一些常用的数据库公用函数分享出来。这个是初稿,以后使用中我会继续完善
    特别是在做报表自动化测试时,数据库的公用函数使用尤其频繁,包括对存储过程的操作


    ' DATABASE公用函数
    '
    '###########################################################################################################
    '###########################################################################################################

    Dim objConnection                          'CONNECTION对象实例
    Dim objRecordSet                                   'RECORDSET对象实例       
    Dim objCommand                                '命令对象实例
    Dim strConnectionString                        '连接字符串

    ' ********************************************************************
    ' 函数说明:连接数据库;
    ' 参数说明:(1)strDBType(数据库类型:如ORACEL;DB2;SQL;ACCESS)
    '           (2)strDBAlias(数据库别名)
    '           (3)strUID(用户名)
    '           (4)strPWD(密码)
    '           (5)strIP(数据库IP地址:仅SQL SERVER 使用)
    '           (6)strLocalHostName(本地主机名:仅SQL SERVER 使用)
    '           (7)strDataSource(数据源:仅ACCESS使用;如d:\yysc.mdb)
    ' 返回结果:无
    ' 调用方法: ConnectDatabase(strDBType, strDBAlias, strUID, strPWD, strIP, strLocalHostName, strDataSource)
    ' ********************************************************************
    Sub ConnectDatabase(strDBType, strDBAlias, strUID, strPWD, strIP, strLocalHostName, strDataSource)
        Set ōbjConnection = CreateObject("ADODB.CONNECTION")                '1 - 建立CONNECTION对象的实例
       
        Select Case UCase(Trim(strDBType))
            Case "ORACLE"
                strConnectionString = "Driver={Microsoft ODBC for Oracle};Server=" & strDBAlias & ";Uid="_
                    & strUID & ";Pwd=" & strPWD & ";"                                '2 - 建立连接字符串
                objConnection.Open strConnectionString                                '3 - 用Open 方法建立与数据库连接
            Case "DB2"
                strConnectionString = "Driver={IBM DB2 ODBC DRIVER};DBALIAS=" & strDBAlias & ";Uid="_
                    & strUID & ";Pwd=" & strPWD & ";"                               
                objConnection.Open strConnectionString                               
            Case "SQL"
                 strConnectionString = "DRIVER=SQL Server; SERVER=" & strIP & "; UID=" & strUID & "; PWD="_
                     & strPWD & "; APP=Microsoft Office 2003;WSID=" & strLocalHostName & "; DATABASE=" & strDBAlias & ";"
                objConnection.Open strConnectionString                                           
            Case "ACCESS"
                strConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" & strDataSource &_
                    ";Jet OLEDB:Database Password=" & strPWD & ";"
                objConnection.Open strConnectionString                                                 
            Case Else
                MsgBox "输入的数据库类型格式有误" & vbCrLf & "支持的数据库类型格式:ORACLE;DB2;SQL;ACCESS;EXCEL"
        End Select
       
        If (objConnection.State = 0) Then
            MsgBox "连接数据库失败!"
        End If
       
    End Sub


    ' ********************************************************************
    ' 函数说明:查询数据库(查询单列);
    ' 参数说明:  (1)strSql:SQL语句
    '           (2)strFieldName:字段名
    '           (3)str_Array_QueryResult:数组名(用来返回单列查询结果)
    ' 返回结果:  intArrayLength:查询数据库返回的记录行数
    '           str_Array_QueryResult:数组名(用来返回单列查询结果)
    ' 调用方法: intArrayLength = QueryDatabase(strSql, strFieldName, str_Array_QueryResult)
    ' ********************************************************************
    Function QueryDatabase(strSql, strFieldName, str_Array_QueryResult)
        Dim intArrayLength                                                                                     '数组长度
         Dim i
       
        i = 0   
        str_Array_QueryResult = Array()                                '重新初始化数组为一个空数组
       
        Set ōbjRecordSet = CreateObject("ADODB.RECORDSET")                '4 - 建立RECORDSET对象实例
        Set ōbjCommand = CreateObject("ADODB.COMMAND")              '5 - 建立COMMAND对象实例
        objCommand.ActiveConnection = objConnection
        objCommand.CommandText = strSql
            objRecordSet.CursorLocation = 3
            objRecordSet.Open objCommand                            '6 - 执行SQL语句,将结果保存在RECORDSET对象实例中
       
        intArrayLength = objRecordSet.RecordCount                  '将查询结果的行数作为数组的长度
       
        If intArrayLength > 0 Then
                    ReDim str_Array_QueryResult(intArrayLength-1)
                   
                    Do While NOT objRecordSet.EOF                                                '将数据库查询的列值赋值给数组            
                        str_Array_QueryResult(i) = objRecordSet(strFieldName)
                            'Debug.WriteLine str_Array_QueryResult(i)
                            objRecordSet.MoveNext
                            i = i + 1
                    Loop
    '        Else
                    'ReDim str_Array_QueryResult(0)      
                    'str_Array_QueryResult(0) = ""     
        End If
       
        QueryDatabase = intArrayLength
    End Function


    ' ********************************************************************
    ' 函数说明:更新数据库;包括INSERT、DELETE 和 UPDATE操作
    ' 参数说明:(1)strSql:SQL语句
    ' 返回结果:无
    ' 调用方法: UpdateDatabase(strSql)
    ' ********************************************************************
    Sub UpdateDatabase(strSql)
            Dim objCommand
            Dim objField       
           
            Set ōbjCommand = CreateObject("ADODB.COMMAND")
            Set ōbjRecordSet = CreateObject("ADODB.RECORDSET")
            objCommand.CommandText = strSql
            objCommand.ActiveConnection = objConnection
            Set ōbjRecordSet = objCommand.Execute
           
    '        Do Until objRecordSet.EOF
           
    '                For Each objField In objRecordSet.Fields
    '                        Debug.Write objField.Name & ": " & objField.Value & "   "
    '                Next
                   
    '                objRecordSet.MoveNext
    '                Debug.WriteLine
    '        Loop       
           
            Set ōbjCommand = Nothing
            Set ōbjRecordSet = Nothing
                   
    End Sub





    ' ********************************************************************
    ' 函数说明:返回符合查询结果的列的长度
    ' 参数说明:(1)strSql:SQL语句
    ' 返回结果:返回符合查询结果的列的长度
    ' 调用方法: MaxLength = GetLenOfField(strSql)
    ' ********************************************************************
    Function GetLenOfField(strSql)
        '如果SQL语句为空,则默认返回的列长度为0,结束函数;否则返回列的实际长度
        If strSql = "" Then
            GetLenOfField  = 0
                    Exit Function
        Else
                Set ōbjRecordSet = CreateObject("ADODB.RECORDSET")                        '4 - 建立RECORDSET对象实例
                Set ōbjCommand = CreateObject("ADODB.COMMAND")              '5 - 建立COMMAND对象实例
                objCommand.ActiveConnection = objConnection
                objCommand.CommandText = strSql
                    objRecordSet.CursorLocation = 3
                    objRecordSet.Open objCommand                                '6 - 执行SQL语句,将结果保存在RECORDSET对象实例中
                
                GetLenOfField = objRecordSet.RecordCount                              '返回符合查询结果的列的长度
           
                    Set ōbjCommand = Nothing       
                    Set ōbjRecordSet = Nothing
            End If
    End Function


    ' ********************************************************************
    ' 函数说明:关闭数据库连接;
    ' 参数说明:无
    ' 返回结果:无
    ' 调用方法: CloseDatabase()
    ' ********************************************************************
    Sub CloseDatabase()
        objRecordSet.Close
        objConnection.Close
       
        Set ōbjCommand = Nothing
        Set ōbjRecordSet = Nothing
        Set ōbjConnection = Nothing
    End Sub
  • QTP中常用的VBS函数

    2008-06-02 20:12:05

    转自:http://bbs.51testing.com/thread-116486-1-1.html

    Left 函数
    返回 Variant (String),其中包含字符串中从左边算起指定数量的字符。
    语法
    Left(string, length)
    Left 函数的语法有下面的命名参数:

    部分        说明          
    string        必要参数。字符串表达式其中最左边的那些字符将被返回。如果 string 包含 Null,将返回 Null。          
    length        必要参数;为 Variant (Long)。数值表达式,指出将返回多少个字符。如果为 0,返回零长度字符串 ("")。如果大于或等于 string 的字符数,则返回整个字符串。         

    说明
    欲知 string 的字符数,使用 Len 函数。
    注意    LeftB 函数作用于包含在字符串中的字节数据。所以 length 指定的是字节数,而不是要返回的字符数。


    Mid 函数
    从字符串中返回指定数目的字符。
    Mid(string, start[, length])
    参数
    string
    字符串表达式,从中返回字符。如果 string 包含 Null,则返回 Null。
    Start
    string 中被提取的字符部分的开始位置。如果 start 超过了 string 中字符的数目,Mid 将返回零长度字符串 ("")。
    Length
    要返回的字符数。如果省略或 length 超过文本的字符数(包括 start 处的字符),将返回字符串中从 start 到字符串结束的所有字符。
    说明
    要判断 string 中字符的数目,可使用 Len 函数。
    下面的示例利用 Mid 函数返回字符串中从第四个字符开始的六个字符:
    Dim MyVar
    MyVar = Mid("VB脚本is fun!", 4, 6) 'MyVar 包含 "scrīpt"。
    注意   MidB 函数与包含在字符串中的字节数据一起使用。其参数不是指定字符数,而是字节数。

    Len 函数
    返回字符串内字符的数目,或是存储一变量所需的字节数。
    Len(string | varname)
    参数
    string
    任意有效的字符串表达式。如果 string 参数包含 Null,则返回 Null。
    Varname
    任意有效的变量名。如果 varname 参数包含 Null,则返回 Null。
    说明
    下面的示例利用 Len 函数返回字符串中的字符数目:
    Dim MyString
    MyString = Len("VBscrīpt") 'MyString 包含 8。
    注意   LenB 函数与包含在字符串中的字节数据一起使用。LenB 不是返回字符串中的字符数,而是返回用于代表字符串的字节数。

    Right 函数
    从字符串右边返回指定数目的字符。
    Right(string, length)
    参数
    string
    字符串表达式,其最右边的字符被返回。如果 string 参数中包含 Null,则返回 Null。
    Length
    数值表达式,指明要返回的字符数目。如果为 0,返回零长度字符串;如果此数大于或等于 string 参数中的所有字符数目,则返回整个字符串。
    说明
    要确定 string 参数中的字符数目,使用 Len 函数。
    下面的示例利用 Right 函数从字符串右边返回指定数目的字符:
    Dim AnyString, MyStr
    AnyString = "Hello World"      ' 定义字符串。
    MyStr = Right(AnyString, 1)    ' 返回 "d"。
    MyStr = Right(AnyString, 6)    ' 返回 " World"。
    MyStr = Right(AnyString, 20)   ' 返回 "Hello World"。
    注意   RightB 函数用于字符串中的字节数据,length 参数指定返回的是字节数目,而不是字符数目。

    InStr 函数
    返回某字符串在另一字符串中第一次出现的位置。
    InStr([start, ]string1, string2[, compare])
    参数
    start
    可选项。数值表达式,用于设置每次搜索的开始位置。如果省略,将从第一个字符的位置开始搜索。如果 start 包含 Null,则会出现错误。如果已指定 compare,则必须要有 start 参数。
    string1
    必选项。接受搜索的字符串表达式。
    string2
    必选项。要搜索的字符串表达式。
    compare
    可选项。指示在计算子字符串时使用的比较类型的数值。有关数值,请参阅“设置”部分。如果省略,将执行二进制比较。
    设置
    compare 参数可以有以下值:

    常数        值        描述          
    vbBinaryCompare        0        执行二进制比较。          
    vbTextCompare        1        执行文本比较。         
    返回值
    InStr 函数返回以下值:

    如果        InStr 返回          
    string1 为零长度        0          
    string1 为 Null        Null          
    string2 为零长度        start          
    string2 为 Null        Null          
    string2 没有找到        0          
    在 string1 中找到 string2        找到匹配字符串的位置          
    start > Len(string2)        0         
    说明
    下面的示例利用 InStr 搜索字符串:
    Dim SearchString, SearchChar, MyPos
    SearchString ="XXpXXpXXPXXP"   ' 要搜索的字符串。
    SearchChar = "P"   ' Search for "P".
    MyPos = Instr(4, SearchString, SearchChar, 1)   ' 在位置 4 进行的文本比较。返回 6。
    MyPos = Instr(1, SearchString, SearchChar, 0)   ' 在位置 1 进行的二进制比较。返回 9。
    MyPos = Instr(SearchString, SearchChar)   ' 默认情况下,进行的是二进制比较(省略了最后的参数)。返回 9。
    MyPos = Instr(1, SearchString, "W")   ' 在位置 1 进行的二进制比较。返回 0(找不到 "W")。
    注意   InStrB 函数使用包含在字符串中的字节数据,所以 InStrB 返回的不是一个字符串在另一个字符串中第一次出现的字符位置,而是字节位置。

    LTrim、RTrim与 Trim 函数
    返回不带前导空格 (LTrim)、后续空格 (RTrim) 或前导与后续空格 (Trim) 的字符串副本。
    LTrim(string)
    RTrim(string)
    Trim(string)
    string 参数是任意有效的字符串表达式。如果 string 参数中包含 Null,则返回 Null。
    说明
    下面的示例利用 LTrim, RTrim, 和 Trim 函数分别用来除去字符串开始的空格、尾部空格、 开始和尾部空格:
    Dim MyVar
    MyVar = LTrim("   vbscrīpt ")   'MyVar 包含 "vbscrīpt "。
    MyVar = RTrim("   vbscrīpt ")   'MyVar 包含 "   vbscrīpt"。
    MyVar = Trim("   vbscrīpt ")   'MyVar 包含 "vbscrīpt"。

    Rnd 函数
    返回一个随机数。
    Rnd[(number)]
    number 参数可以是任意有效的数值表达式。
    说明
    Rnd 函数返回一个小于 1 但大于或等于 0 的值。number 的值决定了 Rnd 生成随机数的方式:

    如果 number 为        Rnd 生成          
    小于零        每次都相同的值,使用 number 作为种子。          
    大于零        序列中的下一个随机数。          
    等于零        最近生成的数。          
    省略        序列中的下一个随机数。         
    因每一次连续调用 Rnd 函数时都用序列中的前一个数作为下一个数的种子,所以对于任何最初给定的种子都会生成相同的数列。
    在调用 Rnd 之前,先使用无参数的 Randomize 语句初始化随机数生成器,该生成器具有基于系统计时器的种子。
    要产生指定范围的随机整数,请使用以下公式:
    Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
    这里, upperbound 是此范围的上界,而 lowerbound 是此范围内的下界。
    注意   要重复随机数的序列,请在使用数值参数调用 Randomize 之前,立即用负值参数调用 Rnd。使用同样 number 值的 Randomize 不能重复先前的随机数序列。

    Randomize 语句
    初始化随机数生成器。
    语法
    Randomize [number]
    可选的 number 参数是 Variant 或任何有效的数值表达式。
    说明
    Randomize 用 number 将 Rnd 函数的随机数生成器初始化,该随机数生成器给 number 一个新的种子值。如果省略 number,则用系统计时器返回的值作为新的种子值。
    如果没有使用 Randomize,则(无参数的)Rnd 函数使用第一次调用 Rnd 函数的种子值。
    注意 若想得到重复的随机数序列,在使用具有数值参数的 Randomize 之前直接调用具有负参数值的 Rnd。使用具有同样 number 值的 Randomize 是不会得到重复的随机数序列的。
    Rnd 函数示例
    本示例使用 Rnd 函数随机生成一个 1 到 6 的随机整数。
    本示例用 Randomize 语句初始化随机数生成器。由于忽略了数值参数, 所以 Randomize 用 Timer 函数的返回值作为新的随机数种子值。

    Dim MyValue
    Randomize   ' 对随机数生成器做初始化的动作。

    MyValue = Int((6 * Rnd) + 1)   ' 生成 1 到 6 之间的随机数值。
    Split函数
    描述
    返回一个下标从零开始的一维数组,它包含指定数目的子字符串。
    语法
    Split(expression[, delimiter[, count[, compare]]])
    Split函数语法有如下几部分:

    部分        描述          
    expression        必需的。包含子字符串和分隔符的字符串表达式 。如果expression是一个长度为零的字符串(""),Split则返回一个空数组,即没有元素和数据的数组。          
    delimiter        可选的。用于标识子字符串边界的字符串字符。如果忽略,则使用空格字符(" ")作为分隔符。如果delimiter是一个长度为零的字符串,则返回的数组仅包含一个元素,即完整的 expression字符串。          
    count        可选的。要返回的子字符串数,–1表示返回所有的子字符串。          
    compare        可选的。数字值,表示判别子字符串时使用的比较方式。关于其值,请参阅“设置值”部分。         

    设置值
    compare参数的设置值如下:

    常数        值        描述          
    vbUseCompareOption        –1        用Option Compare语句中的设置值执行比较。          
    vbBinaryCompare        0        执行二进制比较。          
    vbTextCompare        1        执行文字比较。          
    vbDatabaseCompare        2        仅用于Microsoft Access。基于您的数据库的信息执行比较。         

    Replace 函数
    返回字符串,其中指定数目的某子字符串被替换为另一个子字符串。
    Replace(expression, find, replacewith[, compare[, count[, start]]])
    参数
    expression
    必选项。字符串表达式包含要替代的子字符串。
    Find
    必选项。被搜索的子字符串。
    Replacewith
    必选项。用于替换的子字符串。
    Start
    可选项。expression 中开始搜索子字符串的位置。如果省略,默认值为 1。在和count 关联时必须用
    count
    可选项。执行子字符串替换的数目。如果省略,默认值为 -1,表示进行所有可能的替换。在和 start 关联时必须用。
    Compare
    可选项。指示在计算子字符串时使用的比较类型的数值。有关数值,请参阅“设置”部分。如果省略,缺省值为 0 ,这意味着必须进行二进制比较。
    设置
    compare 参数可以有以下值:

    常数        值        描述          
    vbBinaryCompare        0        执行二进制比较。          
    vbTextCompare        1        执行文本比较。         
    返回值
    Replace 返回以下值:

    如果        Replace 返回          
    expression 为零长度        零长度字符串 ("")。          
    expression 为 Null        错误。          
    find 为零长度        expression 的副本。          
    replacewith 为零长度        expression 的副本,其中删除了所有由 find 参数指定的内容。          
    start > Len(expression)        零长度字符串。          
    count 为 0        expression 的副本。         
    说明
    Replace 函数的返回值是经过替换(从由 start 指定的位置开始到 expression 字符串的结尾)后的字符串,而不是原始字符串从开始至结尾的副本。
    下面的示例利用 Replace 函数返回字符串:
    Dim MyString
    MyString = Replace("XXpXXPXXp", "p", "Y")   '二进制比较从字符串左端开始。返回 "XXYXXPXXY"。
    MyString = Replace("XXpXXPXXp", "p", "Y", '文本比较从第三个字符开始。返回 "YXXYXXY"。3,, -1, 1)

    StrComp 函数
    返回一个表明字符串比较结果的值。
    StrComp(string1, string2[, compare])
    参数
    string1
    必选项。任意有效的字符串表达式。
    string2
    必选项。任意有效的字符串表达式。
    Compare
    可选项。指示在计算字符串时使用的比较类型的数值。如果省略,则执行二进制比较。有关数值,请参阅“设置”部分。
    设置
    compare 参数可以有以下值:

    常数        值        描述          
    vbBinaryCompare        0        执行二进制比较。          
    vbTextCompare        1        执行文本比较。         
    返回值
    StrComp 函数有以下返回值:

    如果        StrComp 返回          
    string1 小于 string2        -1          
    string1 等于 string2        0          
    string1 大于 string2        1          
    string1 或 string2 为 Null        Null         
    说明
    下面的示例利用 StrComp 函数返回字符串比较的结果。如果第三个参数为 1 执行文本比较;如果第三个参数为 0 或者省略执行二进制比较。
    Dim MyStr1, MyStr2, MyComp
    MyStr1 = "ABCD": MyStr2 = "abcd"   '定义变量。
    MyComp = StrComp(MyStr1, MyStr2, 1)   ' 返回 0。
    MyComp = StrComp(MyStr1, MyStr2, 0)   ' 返回 -1。
    MyComp = StrComp(MyStr2, MyStr1)   ' 返回 1。

    CInt 函数
    返回表达式,此表达式已被转换为 Integer 子类型的 Variant。
    CInt(expression)
    expression 参数是任意有效的表达式。
    说明
    通常,可以使用子类型转换函数书写代码,以显示某些操作的结果应被表示为特定的数据类型,而不是默认类型。例如,在出现货币、单精度或双精度运算的情况下,使用 CInt 或 CLng 强制执行整数运算。
    CInt 函数用于进行从其他数据类型到 Integer 子类型的国际公认的格式转换。例如对十进制分隔符(如千分符)的识别,可能取决于系统的区域设置。
    如果 expression 在 Integer 子类型可接受的范围之外,则发生错误。
    下面的示例利用 CInt 函数把值转换为 Integer:
    Dim MyDouble, MyInt
    MyDouble = 2345.5678      ' MyDouble 是 Double。
    MyInt = CInt(MyDouble)    ' MyInt 包含 2346。
    注意   CInt 不同于 Fix 和 Int 函数删除数值的小数部分,而是采用四舍五入的方式。当小数部分正好等于 0.5 时, CInt 总是将其四舍五入成最接近该数的偶数。例如, 0.5 四舍五入为 0, 以及 1.5 四舍五入为 2.

    CStr 函数
    返回表达式,该表达式已被转换为 String 子类型的 Variant。
    CStr(expression)
    expression 参数是任意有效的表达式。
    说明
    通常,可以使用子类型转换函数书写代码,以显示某些操作的结果应被表示为特定的数据类型,而不是默认类型。例如,使用 CStr 强制将结果表示为 String。
    CStr 函数用于替代 Str 函数来进行从其他数据类型到 String 子类型的国际公认的格式转换。例如对十进制分隔符的识别取决于系统的区域设置。
    expression 根据下表决定返回的数据:

    如果 expression 为        CStr 返回          
    Boolean        字符串,包含 True 或 False。          
    Date        字符串,包含系统的短日期格式日期。          
    Null        运行时错误。          
    Empty        零长度字符串 ("")。          
    Error        字符串,包含跟随有错误号码的单词 Error。          
    其他数值        字符串,包含此数字。         
    下面的示例利用 CStr 函数把数字转换为 String:
    Dim MyDouble, MyString
    MyDouble = 437.324         ' MyDouble 是双精度值。
    MyString = CStr(MyDouble)  ' MyString 包含 "437.324"。

    LCase 函数
    返回字符串的小写形式。
    LCase(string)
    string 参数是任意有效的字符串表达式。如果 string 参数中包含 Null,则返回 Null。
    说明
    仅大写字母转换成小写字母;所有小写字母和非字母字符保持不变。

    下面的示例利用 LCase 函数把大写字母转换为小写字母:
    Dim MyString
    Dim LCaseString
    MyString = "VBscrīpt"
    LCaseString = LCase(MyString)   ' LCaseString 包含 "vbscrīpt"。
    UCase 函数
    返回字符串的大写形式。
    UCase(string)
    string 参数是任意有效的字符串表达式。如果 string 参数中包含 Null,则返回 Null。
    说明
    只有小写字母被转换成大写字母;所有大写字母和非字母字符均保持不变。
    下面的示例利用 UCase 函数返回字符串的大写形式:
    Dim MyWord
    MyWord = UCase("Hello World")   ' 返回"HELLO WORLD"。

    MsgBox 函数
    在对话框中显示消息,等待用户单击按钮,并返回一个值指示用户单击的按钮。
    MsgBox(prompt[, buttons][, title][, helpfile, context])
    参数
    prompt
    作为消息显示在对话框中的字符串表达式。prompt 的最大长度大约是 1024 个字符,这取决于所使用的字符的宽度。如果 prompt 中包含多个行,则可在各行之间用回车符 (Chr(13))、换行符 (Chr(10)) 或回车换行符的组合 (Chr(13) & Chr(10)) 分隔各行。
    Buttons
    数值表达式,是表示指定显示按钮的数目和类型、使用的图标样式,默认按钮的标识以及消息框样式的数值的总和。有关数值,请参阅“设置”部分。如果省略,则 buttons 的默认值为 0。
    Title
    显示在对话框标题栏中的字符串表达式。如果省略 title,则将应用程序的名称显示在标题栏中。
    Helpfile
    字符串表达式,用于标识为对话框提供上下文相关帮助的帮助文件。如果已提供 helpfile,则必须提供 context。在 16 位系统平台上不可用。
    Context
    数值表达式,用于标识由帮助文件的作者指定给某个帮助主题的上下文编号。如果已提供 context,则必须提供 helpfile。在 16 位系统平台上不可用。
    设置
    buttons 参数可以有以下值:

    常数        值        描述          
    vbOKOnly        0        只显示确定按钮。          
    vbOKCancel        1        显示确定和取消按钮。          
    vbAbortRetryIgnore        2        显示放弃、重试和忽略按钮。          
    vbYesNoCancel        3        显示是、否和取消按钮。          
    vbYesNo        4        显示是和否按钮。          
    vbRetryCancel        5        显示重试和取消按钮。          
    vbCritical        16        显示临界信息图标。          
    vbQuestion        32        显示警告查询图标。          
    vbExclamation        48        显示警告消息图标。          
    vbInformation        64        显示信息消息图标。          
    vbDefaultButton1        0        第一个按钮为默认按钮。          
    vbDefaultButton2        256        第二个按钮为默认按钮。          
    vbDefaultButton3        512        第三个按钮为默认按钮。          
    vbDefaultButton4        768        第四个按钮为默认按钮。          
    vbApplicationModal        0        应用程序模式:用户必须响应消息框才能继续在当前应用程序中工作。          
    vbSystemModal        4096        系统模式:在用户响应消息框前,所有应用程序都被挂起。         
    第一组值 (0 - 5) 用于描述对话框中显示的按钮类型与数目;第二组值 (16, 32, 48, 64) 用于描述图标的样式;第三组值 (0, 256, 512) 用于确定默认按钮;而第四组值 (0, 4096) 则决定消息框的样式。在将这些数字相加以生成 buttons 参数值时,只能从每组值中取用一个数字。
    返回值
    MsgBox 函数有以下返回值:

    常数        值        按钮          
    vbOK        1        确定          
    vbCancel        2        取消          
    vbAbort        3        放弃          
    vbRetry        4        重试          
    vbIgnore        5        忽略          
    vbYes        6        是          
    vbNo        7        否         
    说明
    如果同时提供了 helpfile 和 context,则用户可以按 F1 键以查看与上下文相对应的帮助主题。
    如果对话框显示取消按钮,则按 ESC 键与单击取消的效果相同。如果对话框包含帮助按钮,则有为对话框提供的上下文相关帮助。但是在单击其他按钮之前,不会返回任何值。
    当MicroSoft Internet Explorer使用MsgBox函数时,任何对话框的标题总是包含"VBscrīpt",以便于将其与标准对话框区别开来。
    下面的例子演示了 MsgBox 函数的用法:
    Dim MyVar
    MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
       ' MyVar 包含 1 或 2,这取决于单击的是哪个按钮。

  • DotNetFactory 应用

    2008-06-01 13:35:33

    DotNetFactory对象使我们能够在qtp环境下创建一个.Net的实例,并访问它的方法和属性。而且,我们还可以通过这个对象去访问类的一些静态方法。

    DotNetFactory的CreatInstance方法 语法:

    Set var_CreateInstance = DotNetFactory.CreateInstance (TypeName [,Assembly] [,args])

    1。 Send keys to Active Window  

    Syntax: object.SendKeys( keys, wait )

  • keys - A String that defines the keys to send.
  • wait - Optional. A Boolean that specifies whether or not to wait for keystrokes to get processed before the application continues. True by default.
  • Example:

    Set Keyboard = DotNetFactory.CreateInstance( "Microsoft.VisualBasic.Devices.Keyboard", "Microsoft.VisualBasic" )

    Call Keyboard.SendKeys( "22", True )

     

  • QTP 基础代码收集

    2008-06-01 13:33:49

    1。 将bug添加到QC

    Dim TDConnection
    Set TDConnection = CreateObject("TDApiOle.TDConnection")
     
    TDConnection.InitConnection "http://yovav/tdbin" ' URL for the DB
    TDConnection.ConnectProject "TD76","bella","pino" ' Valid login information
     
    If TDConnection.Connected Then
      MsgBox("Connected to " + chr (13) + "Server " + TDConnection.ServerName _
      + chr (13) +"Project " + TDConnection.ProjectName )
    Else
      MsgBox("Not Connected")
    End If
     
    'Get the IBugFactory
    Set BugFactory = TDConnection.BugFactory
     
    'Add a new empty bug
    Set Bug = BugFactory.AddItem (Nothing)
     
    'fill the bug with relevant parameters
    Bug.Status = "New"
    Bug.Summary = "Connecting to TD"
    Bug.Priority = "4-Very High" ' depends on the DB
    Bug.AssignedTo = "admin" ' user that must exist in the DB's users list
    Bug.DetectedBy = "admin" ' user that must exist in the DB's users list
     
    'Post the bug to DB ( commit )
    Bug.Post

    2。 文件操作函数集:


    ' Creates a specified file and returns a TextStream object that can be used to read from or write to the file.
    ' Example of usage
    ' Set f = CreateFile("d:\temp\beenhere.txt", True)
    ' f.WriteLine Now
    ' f.Close
    Function CreateFile(sFilename, bOverwrite)
        Set fso = CreateObject("scrīpting.FileSystemObject")
        Set CreateFile = fso.CreateTextFile(sFilename, bOverwrite)
    End Function
     
    ' Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
    ' iomode: 1 - ForReading, 2 - ForWriting, 8 - ForAppending
    ' Example of usage
    ' Set f = OpenFile("d:\temp\beenhere.txt", 2, True)
    ' f.WriteLine Now
    ' f.Close

    Function OpenFile(sFilename, iomode, create)
        Set fso = CreateObject("scrīpting.FileSystemObject")
        Set ōpenFile = fso.OpenTextFile(sFilename, iomode, create)
    End Function
     
    ' Appends a line to a file
    ' Example of usage
    ' AppendToFile "d:\temp\beenhere.txt", Now
    Function AppendToFile(sFilename, sLine)
        Const ForAppending = 8
        If sFilename = "" Then
            sFilename = Environment("SystemTempDir") & "\QTDebug.txt"
        End If
        Set f = OpenFile(sFilename, ForAppending, True)
        f.WriteLine sLine
        f.Close
    End Function
     
    ' Writes a line to a file.
    ' Destroys the current content of the file!
    ' Example of usage
    ' WriteToFile "d:\temp\beenhere.txt", Now
    Function WriteToFile(sFilename, sLine)
        Const ForWriting = 2
        If sFilename = "" Then
            sFilename = Environment("SystemTempDir") & "\QTDebug.txt"
        End If
        Set f = OpenFile(sFilename, ForWriting, True)
        f.WriteLine sLine
        f.Close
    End Function

    3。 使用qtp发mail

    ' Example 1
    Function SendMail(SendTo, Subject, Body, Attachment)
        Set ōl=CreateObject("Outlook.Application")
        Set Mail=ol.CreateItem(0)
        Mail.to=SendTo
        Mail.Subject=Subject
        Mail.Body=Body
        If (Attachment <> "") Then
            Mail.Attachments.Add(Attachment)
        End If
        Mail.Send
        ol.Quit
        Set Mail = Nothing
        Set ōl = Nothing
    End Function
     
    ' Example 2
    Function SendMail(SendFrom, SendTo, Subject, Body)
        Set ōbjMail=CreateObject("CDONTS.Newmail")
        ObjMail.From = SendFrom
        ObjMail.To = SendTo
        ObjMail.Subject = Subject
        ObjMail.Body = Body
        ObjMail.Send
        Set ōbjMail = Nothing
    End Function
     

    4。Excel操作函数集合:

    Dim ExcellApp 'As Excel.Application
    Dim excelSheet1 'As Excel.worksheet
    Dim excelSheet2 'As Excel.worksheet
     
    Set ExcelApp = CreateExcel()
     
    'Create a workbook with two worksheets
    ret = RenameWorksheet(ExcelApp, "Book1", "Sheet1", "Example1 Sheet Name")
    ret = RenameWorksheet(ExcelApp, "Book1", "Sheet2", "Example2 Sheet Name")
    ret = RemoveWorksheet(ExcelApp, "Book1", "Sheet3")
     
    'SaveAs the work book
    ret = SaveWorkbook(ExcelApp, "Book1", "D:\Example1.xls")
     
    'Fill worksheets
    Set excelSheet1 = GetSheet(ExcelApp, "Example1 Sheet Name")
    Set excelSheet2 = GetSheet(ExcelApp, "Example2 Sheet Name")
    For column = 1 to 10
        For row = 1 to 10
            SetCellValue excelSheet1, row, column, row + column
            SetCellValue excelSheet2, row, column, row + column
        Next
    Next
     
    'Compare the two worksheets
    ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, False)
    If ret Then
        MsgBox "The two worksheets are identical"
    End If
     
    'Change the values in one sheet
    SetCellValue excelSheet1, 1, 1, "Yellow"
    SetCellValue excelSheet2, 2, 2, "Hello"
     
    'Compare the worksheets again
    ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, True)
    If Not ret Then
        MsgBox "The two worksheets are not identical"
    End If
     
    'save the workbook by index identifier
    SaveWorkbook ExcelApp, 1, ""
     
    'Close the Excel application
    CloseExcel ExcelApp
     
    ' ****************************************** 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

    5。WebTable功能函数集合:

    ' ************************************************** Function Library ********************************
     
    ' Registering both functions
    RegisterUserFunc "WebTable", "ObjectsByMicClass", "ObjectsByMicClass"
    RegisterUserFunc "WebTable", "ItemByKeyColumn", "ItemByKeyColumn"
     
    ' Function: ObjectsByMicClass
    ' Descrīption: Returns a collection of objects all the objects in a
    ' WebTable that have the specified MicClass
    ' Return Value: A Collection of Objects
    ' Arguments:
    ' Obj - Test Object (WebTable)
    ' micClass - The micClass of the objects to retrieve
    '-----------------------------------------------------------------------------------------------------------
    Function ObjectsByMicClass(Obj, micClass)
        Set Table = Obj
        ' Create a collection object to hold the items
        Set ōbjCollection = CreateObject("scrīpting.Dictionary")
        ' Go over all the cells in the table, and look for objects with the specified micClass
        For row=1 to Table.RowCount
            ColumnCount=Table.ColumnCount(row)
            For col=1 to ColumnCount
                For ItemIndex=0 to Table.ChildItemCount(row, col, micClass)-1
                    Set childItem=Nothing
                    Set childItem = Table.ChildItem(row, col, micClass, ItemIndex)
                    If Not childItem is Nothing Then
                         ' If the cell contains a micClass object, add it to the collection
                         ItemKey = objCollection.Count + 1
                         objCollection.Add ItemKey, childItem
                    End if
                Next
            Next
        Next
        Set ōbjectsbyMicClass = objCollection
    End Function
     
     
    ' Function: ItemByKeyColumn
    ' Descrīption: Returns an item from a column, based on the value of a
    ' key column
    ' Return Value: Object
    ' Arguments:
    ' Obj - Test Object (WebTable)
    ' KeyColumnIndex - Index of the KeyColumn
    ' KeyColumnValue - Value to search for in the key column
    ' KeyItemIndex - Index of the value in the key column (if there is
    '                        more than one). If 0, the first item will be used.
    ' TargetColumnIndex - Column from which to retrieve the target item
    ' micClass - The micClass of the target item
    ' TargetItemIndex - Index of the target item to retrieve (if there is
    '                           more than one). If 0, the first item will be used.
    ' ------------------------------------------------------------------------------------------------------------------------------------
    Function ItemByKeyColumn(Obj, KeyColumnIndex, KeyColumnValue, KeyItemIndex, TargetColumnIndex, micClass, TargetItemIndex)
        Table = Obj
        rowCount = Table.RowCount
     
        ' if TargetItemIndex was not specified, use 1 as deafult
        If TargetItemIndex < 1 Then
            TargetItemIndex = 1
        End If
        ' if KeyColumnIndex was not specified, use 1 as default
        If KeyItemIndex < 1 Then
            KeyItemIndex = 1
        End If
     
        ' look for KeyColumnValue in the key column to determine which
        ' row to retrieve the targe item from
        Row = 0
        foundIndex = 0
        While Row <= RowCount And foundIndex < KeyItemIndex
            Row = Row + 1
            CellData = Table.GetCellData(Row, KeyColumnIndex)
            If CellData = KeyColumnValue Then
               foundIndex = foundIndex + 1
            End If
        Wend
        If foundIndex < KeyItemIndex Then
            Exit Function
        End If
     
        ' Now that we know the row, retrieve the item (according to its micClass)
        ' from the target column.
        ChildItemsCount = Table.ChildItemCount(Row, TargetColumnIndex, micClass)
        If ChildItemsCount > =1 And ChildItemsCount >= TargetItemIndex Then
             Set GetItemByKeyColumn = Table.ChildItem(Row, TargetColumnIndex, micClass, TargetItemIndex-1)
        End If
    End Function
     
     
    ' ************************************ Examples that use these functions *******************************************************
     
     
    ' Using the ItemByKeyColumn Function
    Set ōbj = Browser("Table with objects").Page("Itenerary: Mercury Tours").WebTable("Acapulco to Zurich").ItemByKeyColumn(1,"FLIGHT",2,3,"WebElement",1)
    msgbox obj.GetROProperty("innerhtml")
     
    ' Using the ObjectsByMicClass function
    Set collection = Browser("Browser").Page("Page").WebTable("Table").ObjectsByMicClass("WebCheckBox")
    For i=1 to collection.count
        If collection(i).GetROProperty("checked") Then
            collection(i).Set "OFF"
        Else
            collection(i).Set "ON"
        End If
    Next

     

  • 验证页面连接方法

    2008-06-01 11:18:41

    1。 验证baidu上面所有的连接是否可用
    set a= Browser("百度一下,你就知道")
    set b= Browser("百度一下,你就知道").Page("百度一下,你就知道")
    call CheckLinks(a,b)

    Function CheckLinks (BrowserObject,BrowserPage)
    CheckLinks=TRUE
    Dim s_URL,i_CreationTime
    Dim s_LinkOuterText,s_LinkInnerText,s_Linkhref
    s_URL=BrowserPage.GetROProperty("url")
    i_CreationTime=1
    i_LinkCount=BrowserPage.object.links.length - 1

    Dim i_Link

    For i_Link=0 to i_LinkCount
    If Trim(BrowserPage.object.links(i_Link).target)="" Then
    BrowserPage.object.links(i_Link).target="_blank" ' Set the link to open i a new window so that we dont have any change in current window
    End If

    BrowserPage.object.links(i_Link).click
    On error resume next
    Browser("CreationTime:=" & i_CreationTime).sync
    Browser("CreationTime:=" & i_CreationTime).Page("micClass:=Page").sync
    On error goto 0
    Dim s_LinkDetails

    IHTML = Browser("CreationTime:=" & i_CreationTime).Page("micClass:=Page").object.Body.innerHTML
    'Check if page was not able to be displayed
    If (InStr(IHTML,"HTTP 404") <> 0) Or (InStr(IHTML,"cannot be displayed") <> 0) Then
    s_LinkDetails="Link Broken" + vbcrlf + "Link Details:" +vbcrlf
    s_LinkDetails=s_LinkDetails+"OuterText: "+ s_LinkOuterText + vbcrlf
    s_LinkDetails=s_LinkDetails+"InnerText: "+ s_LinkInnerText + vbcrlf
    s_LinkDetails=s_LinkDetails+ "href: " + s_Linkhref+ vbcrlf
    s_LinkDetails=s_LinkDetails+ "Links Open in New Browse: " & bNewBrowser & vbcrlf
    Reporter.ReportEvent micWarning,"Check Link(" & i_Link & ") -> " & s_LinkOuterText ,s_LinkDetails
    CheckLinks=FALSE
    Else
    s_LinkDetails="Link Working" + vbcrlf + "Link Details:" +vbcrlf
    s_LinkDetails=s_LinkDetails+"OuterText: "+ s_LinkOuterText + vbcrlf
    s_LinkDetails=s_LinkDetails+"InnerText: "+ s_LinkInnerText+ vbcrlf
    s_LinkDetails=s_LinkDetails+ "href: " + s_Linkhref+ vbcrlf
    s_LinkDetails=s_LinkDetails+ "Links Open in New Browse: " & bNewBrowser & vbcrlf
    Reporter.ReportEvent micPass,"Check Link(" & i_Link & ") -> " & s_LinkOuterText ,s_LinkDetails
    End If

    Browser("CreationTime:=1").close ' Close the link open.
    Next
    End Function

    列举应用程序:

    Function EnumerateApp(ParentObj, Desc, OperationMethod, PostOperationMethod, RestoreMethod)
       dim ObjCol, CurrentObj, idx
       idx = 0
       ' retrieve a collection of all the objects of the given descrition
       Set ōbjCol = ParentObj.ChildObjects(Desc)
     
       Do While (idx < ObjCol.Count)
          ' get the current object
          set CurrentObj = ObjCol.item(idx)
      
          ' perform the desired operation on the object
          eval("CurrentObj." & OperationMethod)
     
          ' perform the post operations (after the object operation)
          eval(PostOperationMethod & "(ParentObj, CurrentObj)")
     
          ' Return the application to the original state
          eval(RestoreMethod & "(ParentObj, CurrentObj)")
     
           idx = idx + 1
           ' reretrieve the collection of objects
           ' (as the application might have changed)
           Set ōbjCol = ParentObj.ChildObjects(Desc)
       Loop
    End Function
     
    ' ********************************** An Example of usage **********************
    ' Report all the pages refered to by the corrent page
    ' ***********************************************************************************
     
    Function ReportPage(ParentObj, CurrentObj)
        dim FuncFilter, PageTitle
     
        PageTitle = ParentObj.GetROProperty("title")
     
        FuncFilter = Reporter.Filter
        Reporter.Filter = 0
        Reporter.ReportEvent 0, "Page Information", "page title " & PageTitle
        Reporter.Filter = FuncFilter
    End Function
     
    Function BrowserBack(ParentObj, CurrentObj)
        BrowserObj.Back
    End Function
     
    ' save the Report Filter mode
    OldFilter = Reporter.Filter
    Reporter.Filter = 2 ' Enables Errors Only
     
    ' Create the descrīption of the Link object
    Set Desc = Descrīption.Create()
    Desc("html tag").Value = "A"
     
    Set BrowserObj = Browser("creationtime:=0")
    Set PageObj = BrowserObj.Page("index:=0")
     
    ' Start the enumeration
    call EnumerateApp(PageObj, Desc, "Click", "ReportPage", "BrowserBack")
     
    Reporter.Filter = OldFilter ' returns the original filter

  • 数据库操作

    2008-05-25 23:44:29

    1。 显示数据库所有记录:

    Dim oConn, oRst, oFieldDim sql
    set ōConn = CreateObject("ADODB.Connection")
    oConn.Open "QT_Flight32"
    set ōRst = CreateObject("ADODB.recordset")
    oRst.Open "Select * from Orders", oConn
    Do Until oRst.EOF   
     For each oField in oRst.Fields      
       Print oField.Name & " = " & oField.Value  
     Next   
    Print String( 20, "-" )   
    oRst.MoveNext
    loop
    oRst.close
    oConn.close

     

    2。 Database功能收集:


    'Example of How to use functions.

    ''************************************************************************************
    ' Example use DSN created for database of Flight sample application.
    ''************************************************************************************
    SQL="SELECT * FROM ORDERS"
    connection_string="QT_Flight32"
     
    isConnected = db_connect ( curConnection ,connection_string )
    If isConnected = 0 then
        ' execute the basic SQL statement
        set myrs=db_execute_query( curConnection , SQL )
       
        ' report the query and the connection string
        Reporter.ReportEvent micInfo ,"Executed query and created recordset ","Connection_string is ==> " & connection_string & " SQL query is ===> " & SQL
        ' show the number of rows in the table using a record set
        msgBox " Quantity of rows in queried DB ( db_get_rows_count )==> " & db_get_rows_count( myrs )
        ' show the number of rows in the table using a new SQL statement
        msgBox " Quantity of rows in queried DB (db_get_rows_count_SQL ) ==> " & db_get_rows_count_SQL( curConnection , "SELECT COUNT(*) FROM ORDERS" )
     
        ' change a value of a field in an existing row
        rc = db_set_field_value (curConnection, "ORDERS" , "Agents_Name" , "test", "Agents_Name", "AGENT_TESTER")
     
        ' examples of how to retrieve values from the table
        msgBox "val row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
        msgBox "val row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
        msgBox "val row 1 col Name: " & db_get_field_value( myrs , 1 , "Agents_Name" )
        msgBox "val SQL row 1 col Name: " & db_get_field_value_SQL( curConnection , "ORDERS" , 1 , "Agents_Name" )
     
        db_disconnect curConnection
    End If
     
    ''****************************************************************************************
     
     
    ' Database Functions library
    '******************************************************************************************
    'db_connect
    ' ---------------
    ' The function creates a new connection session to a database.
    ' curSession - the session name (string)
    ' connection_string - a connection string
    ' for example the connection_string can be "DSN=SQLServer_Source;UID=SA;PWD=abc123"
    '******************************************************************************************
    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.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
     
    '********************************************************************************************
    ' db_disconnect
    ' ---------------------
    ' The function disconnects from the database and deletes the session.
    ' curSession - the session name (string)
    '********************************************************************************************
    Function db_disconnect( byRef curSession )
        curSession.close
        set curSession = Nothing
    End Function
     
    '*********************************************************************************************
    ' db_execute_query
    ' ---------------------------
    ' The function executes an SQL statement.
    ' Note that a db_connect for (arg1) must be called before this function
    ' curSession - the session name (string)
    ' SQL - an SQL statement
    '**********************************************************************************************
    Function db_execute_query ( byRef curSession , SQL)
        set rs = curSession.Execute( SQL )
        set db_execute_query = rs
    End Function
     
    ''***********************************************************************************************
    ' db_get_rows_count
    ' ----------------------------
    ' The function returns the number of rows in the record set
    ' curRS - variable , contain record set , that contain all values that retrieved from DB by query execution
    ''***********************************************************************************************
    Function db_get_rows_count( byRef curRS )
        dim rows
        rows = 0
        curRS.MoveFirst
        Do Until curRS.EOF
            rows = rows+1
            curRS.MoveNext
        Loop
        db_get_rows_count = rows
    End Function
     
    ''************************************************************************************************
    ' db_get_rows_count_SQL
    ' ------------------------------------
    ' The function returns the number of rows that are the result of a given SQL statement
    ' curSession - the session name (string)
    ' CountSQL - SQL statement
    ''************************************************************************************************
    Function db_get_rows_count_SQL( byRef curSession ,CountSQL )
        dim cur_rs
        set cur_rs = curSession.Execute( CountSQL )
        db_get_rows_count_SQL = cur_rs.fields(0).value
    End Function
     
    ''*************************************************************************************************
    ' db_get_field_value_SQL
    ' -----------------------------------
    ' curSession - variable denote current active connection
    ' tableName - name of the table , where value should be retrieved
    ' rowIndex - row number
    ' colName - the column name.
    '*************************************************************************************************
    Function db_get_field_value_SQL( curSession , tableName , rowIndex , colName )
        dim rs
        SQL = " select " & colName & " from " & tableName
        set rs = curSession.Execute( SQL )

        rs.move rowIndex
        db_get_field_value_SQL = rs.fields(colName).value
    End Function

    '*************************************************************************************************
    ' db_get_field_value
    ' --------------------------
    ' The function returns the value of a single item of an executed query.
    ' Note that a db_execute_query for (arg1) must called before this function
     
    ' curRecordSet - variable , contain record set , that contain all values that retrieved from DB by query execution
    ' rowIndex - the row index number (zero based)
    ' colIndex - the column index number (zero based) or the column name.
    ' returned values
    ' -1 - requested field index more than exists in record set
    '*************************************************************************************************
    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
     
    '*************************************************************************************************
    ' db_set_field_value
    ' ---------------------------
    ' The function changes the value of a field according to a search criteria.
    ' We search for a certain row according to a column name and the desired vale, then we change a value in that row according
    ' to a desired columns
     
    ' curConnection - the session name (string)
    ' tableName - name of the table , where value should be retrieved
    ' colFind - the column we search the criteria in
    ' colFindValue - the value we search in the column
    ' colChange - the column were we want to change the value
    ' colChangeValue - the new value
     
    ' returned values
    ' -1 - requested field index that doesn't exists in the recordset
    '*************************************************************************************************
    Function db_set_field_value(curConnection, tableName , colFind , colFindValue, colChange, colChangeValue)
        dim curRow
        dim updateSQL
        dim checkSQL
     
        checkSQL = "select * from Details"
        set myrs1 = db_execute_query( curConnection , SQL )
        myrs1.MoveFirst
        count_fields = myrs1.fields.count
        If ( TypeName(colFind)<> "String" ) or ( TypeName(colChange)<> "String" ) then
            db_set_field_value = -1 'requested field index that doesn't exists in the record set
        Else
            updateSQL = "UPDATE " & tableName & " SET " & colChange & "='" & colChangeValue & "' WHERE " & colFind & "='" & colFindValue & "'"
            set myrs1 = db_execute_query( curConnection , updateSQL )
            db_set_field_value = 1 'operation suceeded
        End If
    End Function
     
    '*************************************************************************************************
    ' db_add_row
    ' -----------------
    ' The function adds a new row to the desired table
     
    ' curConnection - variable , contains a recordset , that contains all the values to be retrieved from DB by query execution
    ' tableName - name of the table , where value should be retrieved from
    ' values - array that contains values to be entered in a new row to the table.

    ' Note: the function must receive values for all the columns in the table!
    ' returned values
    ' -1 - the number of values to be entered to the table doesn't fit the number of columns
    ' 1 - execution of the query succeed and the data was entered to the table
    '*************************************************************************************************
    Function db_add_row(curConnection, tableName , byRef values)
        dim i
        dim updateSQL
        dim myrs1
     
        updateSQL = "INSERT INTO " & tableName & " VALUES ("
        arrLen = UBound (values) - LBound (values) + 1
     
        set myrs1=db_execute_query( curConnection , SQL )
        myrs1.MoveFirst
        count_fields = myrs1.fields.count
        ' check if numbers of values fit the numbers of columns
        If arrLen <> count_fields then
            db_add_row = -1
        Else
            For i = 0 to arrLen-1
                updateSQL = updateSQL & values (i)
                If i <> arrLen-1 then
                    updateSQL = updateSQL & ","
                End If
            Next
            updateSQL = updateSQL & ")"
            set myrs1 = db_execute_query( curConnection , updateSQL )
            db_add_row = 1
         End If
    End Function
     
    '*************************************************************************************************
    ' represent_values_of_RecordSet
    ' ---------------------------------------------
    ' the function reports all the values on fields in a record set
    ' curRS - variable , contains the recordset , that contains all the values that were retrieved from the DB by the query execution
    '*************************************************************************************************
    Function represent_values_of_RecordSet( myrs)
        dim curRowString
        myrs.MoveFirst
        reporter.ReportEvent 4,"Fields quantity" , myrs.fields.count
        count_fields = myrs.fields.count-1
        curRow=0
        Do Until myrs.EOF
            curRowString= ""
            curRow = curRow+1
            For ii=0 to count_fields
                curRowString = curRowString& "Field " &"==> " & myrs.fields(ii).Name &" : Value ==>" & myrs.fields(ii).Value & vbCrLf
            Next
            myrs.MoveNext
            reporter.ReportEvent 4,"Current row"& curRow , curRowString
        Loop
    End Function

     

  • DeviceReplay 用法

    2008-05-25 22:29:58

      当我想对UI上的控件做一些特定的操作的时候,例如鼠标左右键点击,键盘输入字符串等,特别是在Object.Set和Object.Type没法使用的时候,DeviceReplay就显得非常有用。

    DeviceReplay使用的前提是:

    1. 应用程序窗口被激活。

    对窗口应用程序: 可以使用Window( "W" ).Activate micLeftBtn

    对网页应用程序: 可以使用

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

    Window( "hwnd:=" & hwnd ).Activate micLeftBtn

    2. 目标控件为焦点。

    WebEdit( "WE" ).object.focus 或者 WebEdit( "WE" ).FireEvent "onfocusin"

    使用以下方法可以判断当前哪些键是否按下:(Microsoft.VisualBasic.Devices.Keyboard

    Set Keyboard = DotNetFactory.CreateInstance( "Microsoft.VisualBasic.Devices.Keyboard", "Microsoft.VisualBasic" )

    Print CBool( Keyboard.AltKeyDown )

    Print CBool( Keyboard.CapsLock )

    Print CBool( Keyboard.CtrlKeyDown )

    Print CBool( Keyboard.NumLock )

    Print CBool( Keyboard.ScrollLock )

    Print CBool( Keyboard.ShiftKeyDown )

    注意:使用DotNetFactory的时候要注意数据类型的转换

    使用以下方法可以判断当前鼠标的位置:(System.Windows.Forms.Control)

    Set ctlr = DotNetFactory.CreateInstance("System.Windows.Forms.Control")

    For i = 1 To 10

       Wait 2

       Print "1. X=" & ctlr.MousePosition.X & "; Y=" & ctlr.MousePosition.Y

    Next

     

    DeviceReplay有以下常用方法:

    1。 object.SendString( str )

    Set deviceReplay = CreateObject( "Mercury.DeviceReplay" )

    SystemUtil.Run "notepad.exe", "", "", "open"

    ' ** this line always identifies the notepad window.

    Window( "nativeclass:=Notepad", "index:=0″ ).Activate micLeftBtn

    deviceReplay.SendString( "DeviceReplay" )

    Set deviceReplay = Nothing

    2。 object.KeyDown( key )|object.KeyUp( key )

    Const VK_SHIFT = 42

    Const VK_RETURN = 28

    Set deviceReplay = CreateObject( "Mercury.DeviceReplay" )

    SystemUtil.Run "notepad.exe", "", "", "open"

    Window( "nativeclass:=Notepad", "index:=0″ ).Activate micLeftBtn

    ' ** Typing uppercase

    deviceReplay.KeyDown VK_SHIFT

    deviceReplay.SendString( "devicereplay" )

    deviceReplay.PressKey VK_RETURN

    deviceReplay.KeyUp VK_SHIFT

    ' ** Typing in lower case

    deviceReplay.SendString( "devicereplay" )

    Set deviceReplay = Nothing

    3。 object.PressKey( key )

    Const VK_O = 24 : Const VK_F = 33

    Const VK_CONTROL = 29 : Const VK_ESCAPE = 1 : Const VK_MENU = 56

    Set deviceReplay = CreateObject( "Mercury.DeviceReplay" )

    SystemUtil.Run "notepad.exe", "", "", "open"

    Window( "nativeclass:=Notepad", "index:=0″ ).Activate micLeftBtn

    Wait 1

    ' ** Opening the menu Alt + F + O

    deviceReplay.PressKey VK_MENU

    deviceReplay.PressKey VK_F

    deviceReplay.PressKey VK_O

    Wait 2

    ' ** Closing the menu

    deviceReplay.PressKey VK_ESCAPE

    deviceReplay.SendString "Open menu was closed."

    Set deviceReplay = Nothing

    4. object.PressNKeys( key, N )


    用于模拟连续多次按某个键。

    5. object.DragAndDrop( dragX, dragY, dropX, dropY, Button )

    LEFT_MOUSE_BUTTON = 0

    MIDDLE_MOUSE_BUTTON = 1

    RIGHT_MOUSE_BUTTON = 2

    等同于object.MouseDown( x, y, Button ), object.MouseDown( x, y ), object.MouseUp( x, y, Button )的组合

    6. object.MouseClick( x, y, Button )

    7. object.MouseDblClick( x, y, Button )

    8。 object.SetSynchronizationTimeout( object, nSyncTimeout, is_sec)


  • QTP 调用vbs读写xml

    2008-05-17 22:27:08

    摘自: http://bbs.51testing.com/viewthread.php?tid=76590&highlight=%23text

    Dim strXML

    GetXml "c:\Configuration.xml","author"  '这个函数的第一个参数表示xml文件所在路径,第二个参数表示希望获取到的xml节点名,请结合下列例子看
    MsgBox strXML


    Function GetXml (ByVal strXmlFilePath,ByVal xmlNodeName)
            Dim xmlDoc,xmlRoot
           
            Set xmlDoc = CreateObject("Microsoft.XMLDOM") '创建XML DOM对象
            xmlDoc.async = False  '控制加载模式为同步模式(xml树加载完毕后再执行后续代码)
            xmlDoc.load strXmlFilePath        '载入xml文件
            If xmlDoc.parseError.errorCode <> 0 Then
                    MsgBox "XML文件格式不对,原因是:" & Chr(13) &  xmlDoc.parseError.reason
                    Exit Function               
            End If
            Set xmlRoot = xmlDoc.documentElement       
            xmlRecursion xmlRoot,xmlNodeName        '调用xml递归函数传入指定的根和节点名       
            GetXml = True 'xmlRecursion (xmlRoot)
           
    End Function

    Function xmlRecursion(byval xmlNode,byval strNodeName)
            If xmlNode.nodeName = strNodeName And xmlNode.hasChildNodes Then
                    If  xmlNode.childNodes.item(0).nodeName = "#text" Then
                            strXML = strXML & xmlNode.nodeName & ":" & xmlNode.childNodes.item(0).nodeValue & Chr(13)                                               
                    End If               
            End If                       
            If xmlNode.hasChildNodes Then
                    For Each childNodeItem In xmlNode.ChildNodes
                            If childNodeItem.hasChildNodes Then
                                    xmlRecursion childNodeItem,strNodeName                               
                            End If                       
                    Next
            End If       
    End Function

    使用xml文件:

    <?xml version="1.0"?>
      <books>
        <book>
            <author>Carson</author>
            <price format="dollar">31.95</price>
            <pubdate>05/01/2001</pubdate>
        </book>
        <pubinfo>
            <publisher>MSPress</publisher>
            <state>WA</state>
            <author>Randall</author> 
        </pubinfo>
        <abc>
            <user>
                <author>Alex</author>
            </user>
        </abc>
      </books>

    结果:

    author:Carson

    author:Randall

    author:Alex

    附:ms-help://MS.MSDNQTR.v90.en/wd_xml/html/b5e52844-4820-47c0-a61d-de2da33e9f54.htm

    The XML Document Object Model (DOM) class is an in-memory representation of an XML document. The DOM allows you to programmatically read, manipulate, and modify an XML document.

    xml:

     
    <?xml version="1.0"?>
      <books>
        <book>
            <author>Carson</author>
            <price format="dollar">31.95</price>
            <pubdate>05/01/2001</pubdate>
        </book>
        <pubinfo>
            <publisher>MSPress</publisher>
            <state>WA</state>
        </pubinfo>
      </books> 

    The following illustration shows how memory is structured when this XML data is read into the DOM structure.

    XML document structure

    Within the XML document structure, each circle in this illustration represents a node, which is called an XmlNode object. The XmlNode object is the basic object in the DOM tree. The XmlDocument class, which extends XmlNode, supports methods for performing operations on the document as a whole (for example, loading it into memory or saving the XML to a file. In addition, XmlDocument provides a means to view and manipulate the nodes in the entire XML document.

  • VBscript 基础积累

    2008-05-17 17:41:57

    摘自:http://doc.51windows.net/vbscrīpt/?url=/vbscrīpt/dir.htm

    1, 声明变量:

    使用 Option Explicit 语句作为脚本的第一条语句,后面使用变量都必须显示声明,可使用Dim, Public, Private.

    Note:

    Dim A(10) 虽然括号中显示的数字是 10,但由于在 VBscrīpt 中所有数组都是基于 0 的,所以这个数组实际上包含 11 个元素。在基于 0 的数组中,数组元素的数目总是括号中显示的数目加 1。这种数组被称为固定大小的数组。
     ReDim MyArray(25)
     . . . 
     ReDim Preserve MyArray(30) 关键字Preserve可以调节数组维数
    2, 过程调用(对Sub过程):
    Call MyProc(firstarg, secondarg)
    MyProc firstarg, secondarg
    当不使用 Call 语句进行调用时,括号被省略。
    3. VB命名约定:
    常量:这种标识常数的方法依旧可行,但您还可以选择其他方案,用 Const 语句创建真正的常数。这个约定使用大小写混合的格式,并以“con”作为常数名的前缀。例如: conYourOwnConstant
    变量: 
    子类型前缀示例
    BooleanblnblnFound
    BytebytbytRasterData
    Date (Time)dtmdtmStart
    DoubledbldblTolerance
    ErrorerrerrOrderNum
    IntegerintintQuantity
    LonglnglngDistance
    ObjectobjobjCurrent
    SinglesngsngAverage
    StringstrstrFirstName

    对象:

    对象类型 前缀 示例
    3D 面板 pnl pnlGroup
    动画按钮 ani aniMailBox
    复选框 chk chkReadOnly
    组合框、下拉列表框 cbo cboEnglish
    命令按钮 cmd cmdExit
    公共对话框 dlg dlgFileOpen
    框架 fra fraLanguage
    水平滚动条 hsb hsbVolume
    图像 img imgIcon
    标签 lbl lblHelpMessage
    直线 lin linVertical
    列表框 lst lstPolicyCodes
    旋钮 spn spnPages
    文本框 txt txtLastName
    垂直滚动条 vsb vsbRate
    滑块 sld sldScale

    4, VBscrīpt 特性:

    类别 关键字
    数组处理 Array
    Dim, Private, Public, ReDim
    IsArray
    Erase
    LBound, UBound
    赋值 Set
    程序注释 使用 ' 或 Rem 的程序注释
    常数/文字 Empty
    Nothing
    Null
    True, False
    控制流程 Do...Loop
    For...Next
    For Each...Next
    If...Then...Else
    Select Case
    While...Wend
    With
    转换 Abs
    Asc, AscB, AscW
    Chr, ChrB, ChrW
    CBool, CByte
    CCur, CDate
    CDbl, CInt
    CLng, CSng, CStr
    DateSerial, DateValue
    Hex, Oct
    Fix, Int
    Sgn
    TimeSerial, TimeValue
    日期/时间 Date, Time
    DateAdd, DateDiff, DatePart
    DateSerial, DateValue
    Day, Month, MonthName
    Weekday, WeekdayName, Year
    Hour, Minute, Second
    Now
    TimeSerial, TimeValue
    声明 Class
    Const
    Dim, Private, Public, ReDim
    函数, Sub
    属性 Get, 属性 Let, 属性 Set
    错误处理 On Error
    Err
    表达式 Eval
    Execute
    RegExp
    Replace
    Test
    格式化字符串 FormatCurrency
    FormatDateTime
    FormatNumber
    FormatPercent
    输入/输出 InputBox
    LoadPicture
    MsgBox
    文字 Empty
    False
    Nothing
    Null
    True
    数学 Atn, Cos, Sin, Tan
    Exp, Log, Sqr
    Randomize, Rnd
    杂类 Eval 函数
    Execute 语句
    RGB 函数
    对象 Create对象
    Err 对象
    Get对象
    RegExp
    运算符 加法 (+),减法 (-)

    幂(^)
    求余算术运算 (Mod)
    乘法 (*)除法(/)
    整除(\)
    求补(-)
    字符串连接(&)
    Is
    And, Or, Xor
    Eqv, Imp

    选项 Option Explicit
    过程 Call
    函数, Sub
    属性 Get, 属性 Let, 属性 Set
    四舍五入 Abs
    Int, Fix, Round
    Sgn
    scrīpt 引擎 ID scrīptEngine
    scrīptEngineBuildVersion
    scrīptEngineMajorVersion
    scrīptEngineMinorVersion
    字符串 Asc, AscB, AscW
    Chr, ChrB, ChrW
    Filter, InStr, InStrB
    InStrRev
    Join
    Len, LenB
    LCase, UCase
    Left, LeftB
    Mid, MidB
    Right, RightB
    Replace
    Space
    Split
    StrComp
    String
    StrReverse
    LTrim, RTrim, Trim
    变量 IsArray
    IsDate
    IsEmpty
    IsNull
    IsNumeric
    Is对象
    TypeName
    VarType

    5, 正值表达式:

    正则表达式(RegExp)对象

    提供简单的正则表达式支持功能。

    说明

    下面的代码说明了RegExp对象的用法:

    Function RegExpTest(patrn, strng)
      Dim regEx, Match, Matches      ' 建立变量。
      Set regEx = New RegExp         ' 建立正则表达式。
      regEx.Pattern = patrn         ' 设置模式。
      regEx.IgnoreCase = True         ' 设置是否区分字符大小写。
      regEx.Global = True         ' 设置全局可用性。
      Set Matches = regEx.Execute(strng)   ' 执行搜索。
      For Each Match in Matches      ' 遍历匹配集合。
        RetStr = RetStr & "Match found at position "
        RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
        RetStr = RetStr & Match.Value & "'." & vbCRLF
      Next
      RegExpTest = RetStr
    End Function
    MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4")
  • QTP 个人总结 (初级)

    2008-04-22 23:16:54

    1. QTP 识别对象原理

    QTP对每个控件类都定义了一些强制属性和辅助属性。当qtp对对象进行识别的时候,首先qtp会取出控件的所有强制属性,如果这些强制属性能够唯一标识这个控件则选强制属性来标识控件,如不能唯一标识控件,qtp则逐一取出控件类的辅助属性直到能唯一标识控件为止。

    如果使用强制属性和辅助属性还不能唯一标识控件。 则有以下两种可能:

    QTP对控件类的识别使用了智能识别(Smart Identification),qtp会忽略之前对强制属性与辅助属性的识别,这时qtp会使用smart identification 中的 basic filter properties和optional filter properties来对对象进行识别. basic filter properties就是一些控件的基础属性,例如button的Name,这个属性变了button也就变成另外一个button了。

    如果对控件类的识别没有使用Smart Identification,系统会使用Ordinal Identifier来对控件进行识别。

    2. QTP的测试流程。大多自动化测试工具都是使用录制回放这种方式:

    录制:QTP录制方式有三种,标准录制,模拟录制与低级录制。

    标准录制一般就是最常用的,录制对标准控件的一些操作,如对button的click,winEdit的Set value等等。

    模拟录制,可以录制鼠标的轨迹,主要用与绘图此类软件的录制。

    低级录制,与标准录制不同,不是Object.Operation value 而是记录屏幕坐标点上的操作。 稳定性较差。

    录制的时候,QTP会将用户的操作以VBscrīpt的形式保存在Expert View里头,录制的时候还会判断控件是否存在对象库里面,如果没有则创建对象。对象库里面的对象称为 Test Object 与程序UI上的控件对象Run Time Object 相对应。

    和TO、RO相关的几个函数有:

    GetTOProperty():取得仓库对象的某个属性的值
    GetTOProperties():取得仓库对象的所有属性的值 //返回一个对象类型,属性集为对象标识属性集
    SetTOProperty():设置仓库对象的某个属性的值
    GetROProperty():取得实际对象的某个属性的值

    录制完成需要对代码进行修改,增加代码的稳定性与可移植性。

    1. Add Comments. 代码中加必要的解释能增加代码的可读性,利于回归测试中代码的维护。

    2. 增加控制流语句。如程序的登陆,正常流程是输入验证信息,点击登陆按钮进入主界面。若用户已经登陆则系统就应该弹出一个确认框问用户是否需要删除原来的session。 这是录制的教本里面我们就应该加一个判断, 判断是否这个弹出框存在。

    3. 参数化。 QTP 参数化有一下几种方式:1)action parameter. Keyword View -> 右键ActionName ->Action Properties, Parameter tab. 可以配置action的传入参数与传出参数,参数的使用为: strInput = Parameter("input"), input为action的传入参数。 Parameter("output") = strOutput, output为action的输出参数。 2)Environment, 在脚本中使用strTemp = Environment("environmentVariable"). 3)datatable, 使用DataTable.SetCurrentRow(RowVale)  strTemp = DataTable.RowValue(Parameter, SheetID).

    4. CheckPoint.

    5. 同步点. WaitProperty(Property, value, Timeout). Object.exist(Timeout). Wait Time.

    6. QTP错误处理机制:

    QTP 有三种错误处理机制:

    1, 全局错误响应: Test setting中run设置

    全局错误响应是qtp的系统缺省错误处理,当没有使用其他错误处理方式时,系统会自动调用这里指定的方式进行错误处理。

    在整个脚本有效。 若是出错在Function Library,则错误号只存在library,不会传到Action中。

    2, VBscrīpt on Error错误处理: On Error Resume Next

    VBscrīpt的错误处理方式,三种相关方式为:

    a)On Error Resume Next: 一旦这个语句已经被处理,脚本将继续后面的程序,不理会已经出现的错误。

    b)On Error GoTo 0: 使用On Error GoTo 0语句恢复缺省的错误处理行为, 在运行这个语句后, 发生的运行期错误将导致缺省错误处理,在qtp中,缺省的出错处理就是全局错误响应。

    c)Err对象: Err对象有三个属性  Number, Source, Descrīption. Err对象在运行时错误发生的时候赋予新的值,原来的值将被丢弃。 Err对象是全局的, 不受函数调用的影响。 Err对象可以使用clear方法清空。 任何时候使用On Error Resume Next或者On Error GoTo 0都会清空Err对象。

    只对语句所在的函数或Action中该语句之后的代码生效,对于子函数,调用Action均无效。若On Error 语句存在Action中而出错在Function Library则系统会调用全局错误响应处理。若是Action中函数调用,则会返回到使用On Error 语句的环境中。

    3, 错误恢复场景: Recovery Scenario.

    触发条件有:

    a) Pop-up Window

    b) Object state

    c) Test run error.

    d) Application Crash.

    错误恢复有以下几种方式:

    a) Keyboard or mouse operation

    b) Close Application process

    c) Function Call

    d) Restart Microsoft Windows

    7. 关于虚拟对象的使用:

    虚拟对象管理器中显示的虚拟对象集合存储在您的计算机中,而不是随包含虚拟对象步骤的测试或组件存储。这意味着如果您在测试或组件步骤中使用虚拟对象,则仅当在包含正确的虚拟对象定义的计算机中运行时,该对象在运行会话过程中才能被识别。要将您的虚拟对象集合定义复制到另一个计算机,请将您的 <QuickTest 安装文件夹>\dat\VoTemplate 文件夹的内容(或该文件夹中的单个 .vot 集合文件)复制到目标计算机上的相同文件夹中

     <QuickTest 安装文件夹>\dat\VoTemplate 文件夹只有在已经定义虚拟对象的情况下才会出项

    8. 使用RegisterUserFunc注册用户定义的测试对象方法

    RegisterUserFunc TOClass, MethodName, FunctionName

    如果输入已经和指定的对象类关联的方法的名称,则用户定义的函数将覆盖现有方法。如果输入新名称,将添加到对象支持的方法列表中。

    Function MySet (obj, x)

    dim y

    y = obj.GetROProperty("value")

    Reporter.ReportEvent micDone, "previous value", y

    MySet=obj.Set(x)

    End Function

    RegisterUserFunc "WebEdit", "Set", "MySet"

    Browser("MercuryTours").Page("FindFlights").WebEdit("Country").Set "Canada"

    使用UnRegisterUserFunc TOClass, MethodName 可以取消用户注册方法

    9, QTP描述性编程:

    平行于对象库的一种编程方法. Example:

    set EditDesc = Descrīption.Create()

    EditDesc("Name").Value = "userName"

    EditDesc("Index").Value = "0"

    Browser("Welcome: Mercury").Page("Welcome: Mercury").WebEdit(EditDesc).Set "MyName"

    使用描述性编程加正值表达式对于那些测试对象经常动态变化的情况很有用, Example:

    Dim strTemp
    strTemp = "Google.*"
    Browser("百度一下,你就知道").Page("Google").WebEdit("q").Set "abc"
    Browser("百度一下,你就知道").Page("Google").WebButton("Name:="&strTemp).Click

    10, 巧用WebTable的ChildItem方法: Example

    Set ōbjTable = Browser("hao123网址之家--文学小说").Page("hao123网址之家--文学小说").WebTable("起点中文网")
    intRow = 2
    intCol = 2
    ' 通过ChildItem获取单元格中的链接对象
    Set ōbjLink = objTable.ChildItem(intRow, intCol, "Link" , 0)
    ' 单击链接
    objLink.click

  • QTP tips

    2008-04-17 21:26:59

    1) How to add a constant number in a datatable?
    This is more to do with MS excel then QTP!! but useful to know because at times it becomes frustrating to the novices.
    Just append ' to the number
    Ex: if you wish to enter 1234567 in datatable then write it as '1234567

    2) How can i check if a parameter exists in DataTable or not?
    The best way would be to use the below code:
    on error resume next
    val=DataTable("ParamName",dtGlobalSheet)
    if err.number<> 0 then
    'Parameter does not exist
    else
    'Parameter exists
    end if

    3) How can i check if a checkpoint passes or not?
    chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
    if chk_PassFail then
    MsgBox "Check Point passed"
    else MsgBox "Check Point failed"
    end if

    4) My test fails due to checkpoint failing, Can i validate a checkpoint without my test failing due to checpoint failure?
    Reporter.Filter = rfDisableAll 'Disables all the reporting stuff
    chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
    Reporter.Filter = rfEnableAll 'Enable all the reporting stuff
    if chk_PassFail then
    MsgBox "Check Point passed"
    else
    MsgBox "Check Point failed"
    end if

    5) What is the difference between an Action and a function?
    Action is a thing specific to QTP while functions are a generic thing which is a feature of VB scrīpting. Action can have a object repository associated with it while a function can't. A function is just lines of code with some/none parameters and a single return value while an action can have more than one output parameters.

    6) Where to use function or action?
    Well answer depends on the scenario. If you want to use the OR feature then you have to go for Action only. If the functionality is not about any automation scrīpt i.e. a function like getting a string between to specific characters, now this is something not specific to QTP and can be done on pure VB scrīpt, so this should be done in a function and not an action. Code specific to QTP can also be put into an function using DP. Decision of using function/action depends on what any one would be comfortable using in a given situation.

    7) When to use a Recovery Scenario and when to us on error resume next?
    Recovery scenarios are used when you cannot predict at what step the error can occur or when you know that error won't occur in your QTP scrīpt but could occur in the world outside QTP, again the example would be "out of paper", as this error is caused by printer device driver. "On error resume next" should be used when you know if an error is expected and dont want to raise it, you may want to have different actions depending upon the error that occurred. Use err.number & err.descrīption to get more details about the error.

    8) How to use environment variable?
    A simple defintion could be... it is a variable which can be used across the reusable actions and is not limited to one reusable action.
    There are two types of environment variables:
    1. User-defined
    2. Built-in
    We can retrieve the value of any environment variable. But we can set the value of only user-defined environment variables.

    To set the value of a user-defined environment variable:
    Environment (VariableName) = NewValue

    To retrieve the value of a loaded environment variable:
    CurrValue = Environment (VariableName)

    Example
    The following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable.

    Environment.Value("MyVariable")=10
    MyValue=Environment.Value("MyVariable")

    9) What are the files and subfolders of a QuickTest Professional test?
    The files and folders hold binary and text data that are required for the test to run successfully.
    The following table provides a descrīption, the type, and comments regarding the files that make up a QuickTest Professional test.

    File Name

    Descrīption

    Type

    Comments Regarding File

    Test.tsp

    Test settings

    Binary

    Do not edit

    Default.xls

    Data table parameters

    Excel similar

    Can be edited using Excel

    Parameters.mtr

    Parameterization information

    Binary

    Do not edit

    Action

    Action folder (See other table)

    <!--[if !supportEmptyParas]--> <!--[endif]-->


    <!--[if !supportEmptyParas]--> <!--[endif]-->


    Default.cfg

    Load test configuration file

    Text

    Do not edit

    Default.prm

    Load test configuration file

    Text

    Do not edit

    Default.usp

    Load test configuration file

    Text

    Do not edit

    .usr

    Load test configuration file

    Text

    Do not edit

    Thick_usr.dat

    Load test configuration file

    Text

    Do not edit

    Thin_usr.dat

    Load test configuration file

    Text

    Do not edit

    Files within Action folder:

    File Name

    Descrīption

    Type

    Comments Regarding File

    scrīpt.mts

    Action scrīpt

    Text

    Edit text preceding the @@ sign only

    Resource.mtr

    Object Repository

    Binary

    Do not edit

    Snapshots

    Active screen files

    Folder

    Do not edit

    There are few more files extensions like

    .MTB Batch File
    .LCK Locked


    10) How to rename a checkpoint (QTP 9.0)?
    Example:
    Window("Notepad").WinEditor("Edit").Check CheckPoint("Edit")
    In the above example, the user would like to change the name of the CheckPoint object from "Edit" to something more meaningful.
    Note:
    This functionality is new to QuickTest Professional 9.0.This is not available for QTP 8.2 and below.
    1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object in Expert View.
    2. Select "Checkpoint Properties" from the pop-up menu.
    3. In the Name field, enter the new checkpoint name.
    4. Click . The name of the checkpoint object will be updated within the scrīpt.
    Example:
    Window("Notepad").WinEditor("Edit").Check CheckPoint("NewCheckPointName")
    Note:
    You must use the QuickTest Professional user interface to change the name of the checkpoint. If you manually change the name of the checkpoint in the scrīpt, QuickTest Professional will generate an error during replay. The error message will be similar to the following:

    "The "" CheckPoint object was not found in the Object Repository. Check the Object Repository to confirm that the object exists or to find the correct name for the object."

    The CheckPoint object is not a visible object within the object repository, so if you manually modify the name, you may need to recreate the checkpoint to resolve the error.

    <!--[if !supportEmptyParas]--> <!--[endif]-->

    11) Does QuickTest Professional support Internet Explorer 7.0?
    QuickTest Professional 9.1
    QuickTest Professional 9.1 supports Microsoft Internet Explorer 7.0 Beta 3. Internet Explorer version 7.0 is now certified to work and to be tested with QuickTest Professional version 9.1.
    QuickTest Professional 9.0
    QuickTest Professional 9.0 supports Internet Explorer 7.0 Beta 2.
    QuickTest Professional 8.2 and below
    QuickTest Professional 8.2 and below do not include support for Internet Explorer 7.0.

    Does QuickTest Professional support Firefox?
    QuickTest Professional 9.1 and 9.2
    QuickTest Professional 9.1 provides replay support for Mozilla Firefox 1.5 and Mozilla Firefox 2.0 Alpha 3 (Alpha-level support for Bon Echo 2.0a3).
    Notes:

    QuickTest Professional 9.1 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.

    The .Object property for web objects is not supported in FireFox.

    QuickTest Professional 9.0
    QuickTest Professional 9.0 provides replay support for Mozilla FireFox 1.5.
    Notes:

    QuickTest Professional 9.0 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.

    The .Object property for web objects is not supported in FireFox.

    QuickTest Professional 8.2 and below

    QuickTest Professional 8.2 and below do not have support for Firefox.


    <!--[if !supportLineBreakNewLine]-->12) Problem
    After Quick Test Professional is started, Windows Media will not start. It returns the error message "wmplayer.exe has generated errors and will be closed by Windows. You will need to restart the program. An error log is being created."

    If you start Window's Media Player first, it will continue to work normally after starting QuickTest Professional.

    Solution:

    Include the Windows Media Player's executable in the NoBBTApps section of the mic.ini file

    1. Close QuickTest Professional.
    2. Go to \bin\mic.ini.
    3. Include wmplayer.exe in the NoBBTApps section of mic.ini file.

    Example:
    [NoBBTApps]
    wmplayer.exe=rek

    4. Save the mic.ini file and restart QuickTest Professional.

    13) What is the lservrc file in QTP?

    The lservrc file contains the license codes that have been installed

    The lservrc file contains the license codes that have been installed. Whenever a new license is created, the license code is automatically added to this file. The lservrc file is a text file, with no extension.

    File Location:

    1) For a Concurrent (Floating) license installation:

    "#server installation directory#\#language#"

    Example:
    C:\Program Files\XYZ Technologies\ABC Server\English\lservrc

    2) For a Seat (Stand-alone) license installation:

    #AQT/QTP installation directory#\bin"

    Example:
    C:\Program Files\Mercury Interactive\QuickTest Professional\Bin\lservrc


    14) What to do if you are not able to run QTP from quality center?
    This is for especially for newbies with QTP.
    Check that you have selected Allow other mercury products to run tests and components from Tools--> Options--> Run Tab.

    15) Does QuickTest Professional support Macintosh operating systems?
    No, QTP is not expected to run on this OS.

    16) The follow situation need to use Parentheses.

    When programming in VBscrīpt, it is important that you follow the rules for using or not using parentheses () in your statements.

    You must use parentheses around method arguments if you are calling a method that returns a value and you are using the return value. For example, use parentheses around method arguments if you are returning a value to a variable, if you are using the method in an If statement, or if you are using the Call keyword to call an action. You also need to add parentheses around the name of a checkpoint if you want to retrieve its return value.

    Tip: If you receive an Expected end of statement error message when running a step in your test, it may indicate that you need to add parentheses around the arguments of the step's method.

    Following are several examples showing when to use or not use parentheses.

    The following example requires parentheses around method arguments, since it returns a value to a variable.

    Set WebEditObj = Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").ChildItem (8, 2, "WebEdit", 0)

    WebEditObj.Set "Example"

    The following example requires parentheses around method arguments, since Call is being used.

    Call RunAction("BookFlight", oneIteration)

    The following example requires parentheses around method arguments, since the method is used in an If statement.

    If Browser("index").Page("index").Link("All kind of").WaitProperty("attribute/readyState", "complete", 4) Then Browser("index").Page("index").Link("All kind of").Click

    The following example requires parentheses around method arguments, since it returns the value of the checkpoint.

    a = Browser("MyBrowser").Page("MyPage").Check (CheckPoint("MyProperty"))

    The following example does not require parentheses around the Click method arguments, since it does not return a value.

    Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").Click 3,4

    17) Encrypts a string.

    In the following example, a password is taken from a database and encrypted using the Encrypt method, and then placed in the password edit box using the SetSecure method.

    pwd = "GetPasswordfromSomewhere"

    e_pwd = Crypt.Encrypt(pwd)

    Browser("dfgd").Dialog("pass").WinEdit("pwd").SetSecure e_pwd

    18) Environment object example:

    The following example uses the ExternalFileName property to check whether an environment variable file is loaded, and if not, loads a specific file and then displays one of the values from the file.

    'Check if an External Environment file is loaded and if not, load it.

    fileName = Environment.ExternalFileName

    If (fileName = "") Then

           Environment.LoadFromFile("C:\Environment.xml")

    End If

    'display value of one of the Environment variables from the External file

    msgbox Environment("MyVarName")

     

  • 转: QTP小结

    2008-04-15 22:28:09

    1.在测试中我们使用QTP调试脚本的时候一般就是DEBUG或者MSGBOX察看一些信息,其实有时候也可以使用print来实现批量的察看信息但是不影响程序运行.
    运行脚本:

    复制内容到剪贴板
    代码:
    a="100"
    print a
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    2.取datatable特定行的数据可以这样使用
    运行脚本:
    复制内容到剪贴板
    代码:
    DataTable.GetSheet("Action1").GetParameter("test").ValueByRow(4)
    ~~~~~~~~~~~~~~~~~~
    3.Wait Seconds [, Milliseconds]可以精确到毫秒.
    ~~~~~~~~~~~~~~~~~~
    4.在自定义的function里面数组作为返回值.
    运行脚本:
    复制内容到剪贴板
    代码:
    circuit = "399937"
    Function trimString(circuit)
    Dim holdArray(5)
    holdArray(0) = Left(circuit, 2)
    holdArray(1) = Right(circuit, 2)
    msgbox holdArray(0) 'showed 39
    trimString = holdArray' I get an out of range error here
    End Function
    dim myArray
    'here I want to assign the return array to another array
    myArray = trimString(circuit)
    ' and then call one element from it
    msgbox myArray(1)
    ~~~~~~~~~~~~~~~
    5.计算一个操作的时间.
    运行脚本:
    复制内容到剪贴板
    代码:
    Browser("Browser").Page("Page").Image("getRates").Click
    var_StartTime = Timer
    Browser("Browser").Page("Page").Sync
    Browser("Browser").Page("Page").Check CheckPoint("Check1")
    var_EndTime = Timer
    intRespTime = round ((var_EndTime - var_StartTime), 2 )
    msgbox (intRespTime)
    ~~~~~~~~~~~~~~~
    6.取得指定sheet(datatable)的行数和列数(也可以理解为参数个数)
    复制内容到剪贴板
    代码:
    paramcount = DataTable.GetSheet("Action1").GetParameterCount
    msgbox "There are " &paramcount&"columns in the data sheet."
    rowcount = DataTable.GetSheet("Action1").GetRowCount
    msgbox "There are " &rowcount&"rows in the data sheet."
    ~~~~~~~~~~
    7.一种设置全局变量的方法GlobalDictionary
    'Part 1.
    '***********************************************************************************************************
    复制内容到剪贴板
    代码:
    Dim WshShell
    Set WshShell =CreateObject("Wscrīpt.Shell")
    WshShell.RegWrite "HKCU\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects\GlobalDictionary\ProgID", "scrīpting.Dictionary","REG_SZ"
    Set WshShell = Nothing
    '*********************************************************************************************************************
    'Part 2.
    '*****************************************************************************************
    复制内容到剪贴板
    代码:
    GlobalDictionary.Add "ParamName", "ParamValue"
    Msgbox GlobalDictionary.Item("ParamName")
    GlobalDictionary.Item("ParamName")="***********"
    Msgbox GlobalDictionary.Item("ParamName")
    Msgbox GlobalDictionary.Exists("ParamName")
    GlobalDictionary.Remove("ParamName")
    Msgbox GlobalDictionary.Exists("ParamName")
    '*********************************************************************************************
    ~~~~~~~~~~~
    8.关掉多余的IE窗口
    复制内容到剪贴板
    代码:
    SystemUtil.CloseProcessByWndTitle "51testing", True
    ~~~~~~~~~~~~~~~~~~
    9.Execute 的用法,这个用法在一些特殊时候很有用的.
    复制内容到剪贴板
    代码:
    x="4"
    Execute "Dim A_" & x
    Execute "A_" & x &"=99"
    Msgbox Eval("A_" & x)  
    ~~~~~~~~~~~~~~~~~~~
    10.GetLastError的介绍,看字面就是取运行最后一个错误
    复制内容到剪贴板
    代码:
    x = GetLastError
    msgbox(DescribeResult(x))
    这样可以在程序里面判断程序运行时候是否出错了.
    ~~~~~~~~~~~~~~~~~
    11.把weblist抓图下来
    复制内容到剪贴板
    代码:
    Setting.WebPackage("ReplayType") = 2 'Default is 1
    Browser(".").Page(".").WebList(".").Click
    Desktop.CaptureBitmap "C:\Test.bmp",True
    Setting.WebPackage("ReplayType") = 1
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    12.Reporter.ReportEvent的新用法
    transNumber = 12345
    复制内容到剪贴板
    代码:
    Reporter.ReportEvent micPass, "TransactionNumber", "<DIV style='font-size: 7pt; color: white'>&</DIV>"&"<B> <FONT COLOR=#000000>"&transNumber&"</FONT></B>"
    Reporter.ReportEvent micPass, "TransactionNumber", "<DIV style='font-size: 7pt; color: white'>&</DIV>"&"<B> <FONT COLOR=red>"&transNumber&"</FONT></B>"
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    13.For循环中step的用法
    复制内容到剪贴板
    代码:
    For K = 1 To 10 step 2
              msgbox k
    Next
    ~~~~~~~~~~~~~~~~~~~~~~~
    14.Option Explicit,大家都知道VB scrīpt里面是可以不申明变量直接使用,但是有时候我们为了脚本的规范,尽量申明使用的变量,这样你就用一下Option Explicit吧.
    复制内容到剪贴板
    代码:
    Option Explicit   ' Force explicit variable declaration.
    Dim MyVar   ' Declare variable.
    MyInt = 10   ' Undeclared variable generates error.
    MyVar = 10   ' Declared variable does not generate error.
    ~~~~~~~~~~~~~~~~~~~~~~~
    14.从TXT文件里面读取特定行的数据.
    复制内容到剪贴板
    代码:
    Dim fso, myfile,msg
    Set fso=CreateObject("scrīpting.FileSystemObject")   
    Set myfile = fso.openTextFile("C:\login.txt",1,false)
    '这里设置一个循环看需要读取第几行
    for i=1 to 10
    myfile.SkipLine
    next
    msg=myfile.ReadLine
    myfile.close
  • 数据统计

    • 访问量: 42253
    • 日志数: 40
    • 文件数: 1
    • 建立时间: 2007-08-06
    • 更新时间: 2014-06-10

    RSS订阅

    Open Toolbar