发布新日志

  • tcl/expect

    2008-12-30 18:18:15

    set time_seconds [clock seconds]
    set time_now [clock format $time_seconds -format {%y-%m-%d}]
    #format与{之间有空格,要不出错
    for {set i 1} {$i <= $length_smtp} {incr i} { #第二个{}注意是有效范围,不是中断范围

    exec tcpreplay -i eth1 -r 10 -l 1 $smtp_arr($i) #老提示tcpreplay不是command,原因之一就是

    tcpreplay没有装


    spawn ssh 192.168.201.222
    root@192.168.201.222's password:
    error deleting ......................too long
        while executing
    "file delete [glob -nocomplain *.SMTP]"
     
    --------删除的文件长度也有限制。发现如果删除的文件长度不长,如果是一个的话,就可以删除。

    解决方法,用如下命令:eval exec rm [glob -nocomplain *.SMTP]


    有时注释掉的语句含有}这个的符合时,也引起问题。

    set fileId [open /SMTP_result.txt a 100000]
            puts $fileId "the $i is OK"
            close $fileId
            after 1000

    如果用参数“w”的话,那么写入文件的信息,只取最后一次输出的信息,以前没有。(好处是如果没有

    SMTP_result.txt文件的话,可自动创建);如果改写成"a"参数,则写入的信息是累加的。(资料说:必

    须SMTP_result.txt文件存在,试了下,如果不存在的话,也可自动创建。)


    有时想把返回的数据,放到一个list里面,就会存在这样的问题,当设置一个空list后,用glob把返回的

    数据lappend放到list里面后,
    用lindex返回第一个元素,发现,把所有元素都返回了,看来是当做一个整体了。这个时候,就要用到eval。
    cd path目录

    eval lappend  list [glob *.SMTP]
    lindex $list 0

    其实index最大值,可通过wc -l返回的行数-1来表示。

     

    不是调试信息:
    如果一个变量的值,是几个变量的取值的组合,可用如下来表示:
    set a "xyz[set b "abc"][set c "def"]
    //return xyzabcdef


    求表达式的值,用expr命令。语法 expr arg?arg?
    例如:
    set j [expr 123+90+80]
    //return 293

    改变变量的取值用:incr和append命令。

    连接两个list的命令:concat
    expect1.59> set a {1 2 3 4 5 6 7 8 9 10}
    1 2 3 4 5 6 7 8 9 10
    expect1.60> set b {11 12 13 14 15 16 17 18 19 20}
    11 12 13 14 15 16 17 18 19 20
    expect1.61> concat $a $b
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    expect1.62> lindex $a 0
    1
    expect1.63> lindex $a 1
    2


    把一个列表的值赋给一个空列表:
    expect1.60> set b {11 12 13 14 15 16 17 18 19 20}
    11 12 13 14 15 16 17 18 19 20
    expect1.64> set a {}
    expect1.78> eval "lappend a $b"
    11 12 13 14 15 16 17 18 19 20
    expect1.79> lindex $a 0
    11

    说明:如果在赋值时,不用eval命令,则赋值的结果当做一个值对待。如果
    是这样lappend a $b
    结果为:
    {11 12 13 14 15 16 17 18 19 20}
    用lindex $a 0可看出是当做一个整体。
    expect1.66> lindex $a 0
    11 12 13 14 15 16 17 18 19 20

    还有,如果用了eval,但是不是用双引号,用的是大括号{}
    ,结果也是当做一个整体。用lindex $a 0返回的也是11 12 13 14 15 16 17 18 19 20


    concat 结果赋值:
    expect1.95> set a {}
    expect1.96> set d [concat $a $b]
    11 12 13 14 15 16 17 18 19 20
    expect1.97> set d "[concat $a $b]"
    11 12 13 14 15 16 17 18 19 20
    expect1.98> set d
    11 12 13 14 15 16 17 18 19 20

    看到用[]扩住,如果用""的话,结果就是concat  11 12 13 14 15 16 17 18 19 20,不识别concat命令
    的,不过双引号里面有[]扩住,还是正确的。


    当给某个列表增加数值时,可用linsert命令。中间的是索引,后面是添加的元素,添加在所指索引的前

    面。例如:
    expect1.104> linsert {1 3 {2 2 } 6 7 8 9 } 1 {12 30 2}
    1 {12 30 2} 3 {2 2 } 6 7 8 9

     

    当想把某个列表中的某些元素删除,可用lreplace命令。(删除索引所指的范围元素)。例如:

    expect1.105> lreplace {1 3 6 7 8 9 10 11 12 13 } 2 3 0 9 0
    1 3 0 9 0 8 9 10 11 12 13


    当想返回列表某些值时,用lrange命令。返回的值,用此命令所指的索引决定。例如:
    expect1.107> lrange {1 2 3 4 5 6 7 8 9 10} 3 end
    4 5 6 7 8 9 10

    当想把值添加到另一个变量里面,则用lappend命令。例如:
    expect1.108> lappend a 1 2 3
    1 2 3
    expect1.109> set a
    1 2 3

  • LoadRunner脚本解释分析

    2008-11-04 16:14:31

    seventest 的个人空间一篇文章。可能将来需要就放到自己的个人空间中以备后用。

     

     

    1、获得网站首页
        web_url("www.seventest.net",
            "URL=www.seventest.net/",
            "TargetFrame=",  //
    目标窗口 _BLANK: 打开一个新窗口
                                              _PARENT:
    取代最后一个窗口的父窗口
                                              _SELF:
    取代最后一个窗口

                                              _TOP:
    取代整个页面
            "Resource=0",            //URL
    是否为一个资源  0:不是

                                                         1:

            "RecContentType=text/html", //
    录制过程中,响应报头内容格式
            "Referer=",                 //
    提交网页的URL
            "Snapshot=t1.inf",          //
    快照文件名

            "Mode=HTML",                //
    录制水平: HTML or HTTP.

    HTML level: 指导VuGen录制直观的HTML动作,录制web_url,web_link,web_image。返回的是HTML 页面,而不是脚本和程序。
    HTTP level:
    指导VuGen录制全部的服务器响应。不产生web_link,web_image,web_submit_form。比HTML高级,但当读脚本时不是很直观。
            EXTRARES,                   //
    参数表划分标志(下个标志是一个资源特征表)
           "Url=/dy.css", "Referer=http://www.seventest.net/index.htm", ENDITEM,     //
    资源结束志
       
           "Url=/images/bg_03.gif", "Referer=http://www.seventest.net/index.htm", ENDITEM, 
           "Url=/images/logo-end%2020GAI.swf","Referer=http://www.seventest.net/index.htm", ENDITEM,
            "Url=/images/2.swf", "Referer=http://www.seventest.net/index.htm", ENDITEM,
            LAST);                      //
    特征表结束标志

    2、下载一个游戏
    web_url("Games",
           "URL=ftp://joe:secret@mygames.com/games/archive/loderunner.exe",
           "FtpAscii=1",         //1:
    ASCII模式执行FTP传输
                                            //0:
    二进制模式
           LAST);

    3、百度搜索科学
    Action()
    {
        //
    打开首页

     web_add_cookie ("BAIDUID=AAFDECDD16EF55636CA63DC64381BBEC:FG=1; DOMAIN=www.baidu.com");

    web_add_cookie("BDSTAT=7e00ef72b41d6156ecc574f4a7efce1b9d16fdfaaf51f3debd8f8c5497eef01f3a292df5e2fe587d;DOMAIN=www.baidu.com");

                                 //网络接口的对象表达式,经常用在JavaVB.

                                 //name=VALUE; 必须
                                  //domain=DOMAIN_NAME;
    必须
                                  //expires=DATE;
                                  //path=PATH; (default path is "/")
                                  //secure
                                 //The elements in the Cookie parameter are the same as the elements in the
                                 //Set–Cookie HTTP Response Header.

     web_url("www.baidu.com",
      "URL=http://www.baidu.com/",  
      "TargetFrame=",
      "Resource=0",
      "RecContentType=text/html",
      "Referer=",
      "Snapshot=t1.inf",
      "Mode=HTML",
      EXTRARES,
      "Url=/favicon.ico", "Referer=", ENDITEM,
      LAST);

     web_add_cookie("BAIDUID=AAFDECDD16EF55636CA63DC64381BBEC:FG=1; DOMAIN=s.baidu.com");

     web_add_cookie("BDSTAT=7e00ef72b41d6156ecc574f4a7efce1b9d16fdfaaf51f3debd8f8c5497eef01f3a292df5e2fe587d;

    DOMAIN=s.baidu.com");

     lr_think_time(13);
       //
    搜索科学

     web_submit_data("s",         //
    提交数据

      "Action=http://www.baidu.com/s",    //
    提交数据的HTTP address
      "Method=GET",
      "EncType=",                       //
    编码方式

      "TargetFrame=",
      "RecContentType=text/html",
      "Referer=http://www.baidu.com/",
      "Snapshot=t2.inf",
      "Mode=HTML",               //
    录制水平
      ITEMDATA,
      "Name=wd", "Value=?", ENDITEM,
      "Name=cl", "Value=3", ENDITEM,
      EXTRARES,
      "Url=http://s.baidu.com/w.gif?path=http://www.baidu.com/s?wd=%BF%C6%D1%A7&cl=3&t=1200288916042",

    "Referer=http://www.baidu.com/s?wd=%BF%C6%D1%A7&cl=3", ENDITEM,
      LAST);

     return 0;
    }

     

  • vbs脚本

    2008-09-24 15:49:08

    '''以下为QuickTest和Robot都适用函数  '作者:俞戴龙
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    '获取当前日期
    Public Function Get_Data()
     Dim currentDate
     currentDate = Date
     Get_Data = currentDate
    End Function

    '获取当前时间
    Public Function Get_Time()
     Dim currentTime
     currentTime = Time
     Get_Time = currentTime
    End Function

    '随机函数生成
    '输入值:生成值范围 i~j
    '返回值:随机数
    Public Function Get_RandNum(fromNum,toNum)
     If (fromNum<0) Or (toNum<0) Then
      MsgBox "只接受大于零的输入"
     ElseIf fromNum>toNum then
      MsgBox "起始值必须小于结束值"
     Else
      Dim RunTime
      Randomize  
      RunTime = Int((10 * Rnd) + 1)
      Dim MyValue,i
      For i = 1 To RunTime
       Randomize 
       MyValue = Int(((toNum - fromNum + 1) * Rnd) + (fromNum))
      Next
        Get_randNum=MyValue
       End If
    End Function

    '值交换函数
    Public Sub swap(byref a,byref b)
     Dim c
     c = a
     a = b
     b = c
    End Sub

    '是否是质数函数
    '是质数返回true,否则返回false
    Function IsPrimeNumber(num)
     Dim i,flag
     flag = true
     If num = 1 Then
      flag = False
     ElseIf num < 1 Then
      MsgBox "只能接受大于0的数"
      flag = False
     Else
      For i = 2 To (num - 1)
       If ((num Mod i) = 0) Then
        flag = False
        Exit For
       End If
      Next
     End If 
     IsPrimeNumber = flag
    End Function

    '读指定文本文件指定行内容
    Function ReadLine(pathway, rowcount)
     Dim fso,myfile,i,flag
     flag = 1
     Set fso=CreateObject("scrīpting.FileSystemObject")
     If fso.FileExists(pathway) then
      Set myfile = fso.openTextFile(pathway,1,false)
     Else
      flag = 0
     End If
     
     For i=1 to rowcount-1
      If Not myfile.AtEndOfLine Then
       myfile.SkipLine
      End If
     Next
     
     If flag = 1 then
      If Not myfile.AtEndOfLine Then
       ReadLine = myfile.ReadLine
      Else
       ReadLine = "文本越界"
      End If
      myfile.close
     Else
      ReadLine = "文件不存在"
     End If
    End Function

    '随机生成字符串
    Function MakeString(inputlength)
     Dim I,x,B,A
     If IsNumeric(inputlength) Then
     For I = 1 To inputlength
      A = Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
      Randomize
      x=Get_RandNum(0,35)
      B = A(x)
      makestring =makestring +B
     Next
      MakeString = makestring
     else
      msgbox ("只接受数字输入")
     End If
    End Function

    '启动资源管理器
    Sub ZYGLQ()
     Dim WshShell
     set WshShell = CreateObject("Wscrīpt.Shell")
     WshShell.SendKeys "^+{ESC}"
     Set WshShell = nothing
    End Sub

    '启动运行
    Sub Run()
     Dim WshShell
     set WshShell = CreateObject("Wscrīpt.Shell")
     WshShell.SendKeys "^{ESC}R"
     Set WshShell = nothing
    End Sub

    '发送电子邮件
    Function SendMail(SendTo, Subject, Body, Attachment)
     Dim ol,mail
        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

    '去掉字符串中的重复项
    Function NoRepeat(Inp,Sp)
    Dim aa,flag,words,length,i,j,k,sp1,sp2,cc
     aa = Inp
     Do
      flag = False
      words = Split(aa,Sp)
      length = UBound(words)
      For i = 0 To (length -1)
       sp1 = words(i)
       For j = (i+1) To length
        sp2 = words(j)
        If sp1 = sp2 Then
         flag = True
         aa = ""
         For k = 0 To (j-1)
          aa = aa & words(k) & sp
         Next
         For k = (j + 1) To length
          aa = aa & words(k) & sp
         Next
         
         cc = Len(aa)
         aa = Left(aa,(cc - 1))
        End If
       Next
       If flag = True Then
        Exit For
       End if
      Next
     Loop Until flag = false
     NoRepeat = aa
    End Function

    '求字符串长度(中文算2个西文字符)
    Function GetLen(Str)
            Dim singleStr, i, iCount
            iCount = 0
            For i = 1 to len(Str)
                    singleStr = mid(Str,i,1)
                    If asc(singleStr) < 0 Then
                            iCount = iCount + 2
                    Else
                            iCount = iCount + 1
                    End If  
            Next
            GetLen = iCount
    End Function

    '运行指定程序
    Sub RunApp(command)
     Dim WshShell
     set WshShell = CreateObject("Wscrīpt.Shell")
     WshShell.Exec command
    End Sub

    '求下一天是几号的函数
    Function Nextday(ByVal inputday)
        Dim temp, num, OPYear, OPMonth, OPDay, ret, flag
        temp = Split(CStr(inputday), "-")
        num = UBound(temp) + 1
        ōPYear = temp(0)
        ōPMonth = temp(1)
        ōPDay = temp(2)
        flag = 0

        If ōPMonth = 1 Or ōPMonth = 3 Or ōPMonth = 5 Or ōPMonth = 7 Or ōPMonth = 8 Or ōPMonth = 10 Or ōPMonth = 12 Then
            If OPDay > 31 Or OPDay < 1 Then
                flag = 1
            End If
        ElseIf ōPMonth = 4 Or ōPMonth = 6 Or ōPMonth = 9 Or ōPMonth = 11 Then
            If OPDay > 30 Or OPDay < 1 Then
                flag = 1
            End If
        Else
            If ISLeapYear(OPYear) Then
                If OPDay > 29 Or OPDay < 1 Then
                    flag = 1
                End If
            Else
                If OPDay > 28 Or OPDay < 1 Then
                    flag = 1
                End If
            End If
        End If

        If flag = 1 Or num <> 3 Then
            MsgBox "输入参数不对劲", , "Nextday函数提示"
        Else
            If ōPMonth = 1 Or ōPMonth = 3 Or ōPMonth = 5 Or ōPMonth = 7 Or ōPMonth = 8 Or ōPMonth = 10 Or ōPMonth = 12 Then 'big month
                If ōPDay = 31 Then
                    ōPDay = 1
                    If ōPMonth = 12 Then
                        ōPMonth = 1
                        ōPYear = OPYear + 1
                    Else
                        ōPMonth = OPMonth + 1
                        ōPYear = OPYear
                    End If
                Else
                    ōPDay = OPDay + 1
                End If
            ElseIf ōPMonth = 4 Or ōPMonth = 6 Or ōPMonth = 9 Or ōPMonth = 11 Then                                          'small month
                If ōPDay = 30 Then
                    ōPDay = 1
                    If ōPMonth = 12 Then
                        ōPMonth = 1
                        ōPYear = OPYear + 1
                    Else
                        ōPMonth = OPMonth + 1
                        ōPYear = OPYear
                    End If
                Else
                    ōPDay = OPDay + 1
                End If
            Else                                                                                                           'February
                If ISLeapYear(OPYear) Then
                    If ōPDay = 29 Then
                        ōPDay = 1
                        If ōPMonth = 12 Then
                            ōPMonth = 1
                            ōPYear = OPYear + 1
                        Else
                            ōPMonth = OPMonth + 1
                            ōPYear = OPYear
                        End If
                    Else
                        ōPDay = OPDay + 1
                    End If
                Else
                    If ōPDay = 28 Then
                        ōPDay = 1
                        If ōPMonth = 12 Then
                            ōPMonth = 1
                            ōPYear = OPYear + 1
                        Else
                            ōPMonth = OPMonth + 1
                            ōPYear = OPYear
                        End If
                    Else
                        ōPDay = OPDay + 1
                    End If
                End If
            End If
            ret = OPYear & "-" & OPMonth & "-" & OPDay
            Nextday = ret
        End If
    End Function

    '是否闰年
    Function ISLeapYear(ByVal inYear)
        If ((inYear Mod 4 = 0 And inYear Mod 100 <> 0) Or inYear Mod 400 = 0) Then
            ISLeapYear = True
        Else
            ISLeapYear = False
        End If
    End Function

    '计算两个日期之间相隔几天
    Function Days(ByVal SourceData, ByVal DesData)
        Dim flag, temp1, temp2, OPYear1, OPYear2, OPMonth1, OPMonth2, OPDay1, OPDay2, i, tempDay
        temp1 = Split(SourceData, "-")
        temp2 = Split(DesData, "-")
        If ((UBound(temp1) + 1) <> 3) Or ((UBound(temp2) + 1) <> 3) Then
            MsgBox "输入参数不对劲", , "Days函数提示"
        End If
        OPYear1 = temp1(0)
        OPMonth1 = temp1(1)
        OPDay1 = temp1(2)
        OPYear2 = temp2(0)
        OPMonth2 = temp2(1)
        OPDay2 = temp2(2)
        If CInt(OPYear1) <> CInt(OPYear2) Then
            If CInt(OPYear1) > CInt(OPYear2) Then
                flag = "big"
            ElseIf CInt(OPYear1) < CInt(OPYear2) Then
                flag = "small"
            End If
        Else
            If CInt(OPMonth1) <> CInt(OPMonth2) Then
                If CInt(OPMonth1) > CInt(OPMonth2) Then
                    flag = "big"
                ElseIf CInt(OPMonth1) < CInt(OPMonth2) Then
                    flag = "small"
                End If
            Else
                If CInt(OPDay1) <> CInt(OPDay2) Then
                    If CInt(OPDay1) > CInt(OPDay2) Then
                        flag = "big"
                    ElseIf CInt(OPDay1) < CInt(OPDay2) Then
                        flag = "small"
                    End If
                Else
                    flag = "="
                End If
            End If
        End If

        If (flag = "big") Then
            i = 1
            tempDay = DesData
            Do
                tempDay = Nextday(tempDay)
                i = i + 1
            Loop Until tempDay = SourceData
            i = i - 1
        ElseIf (flag = "small") Then
            i = 1
            tempDay = SourceData
            Do
                tempDay = Nextday(tempDay)
                i = i + 1
            Loop Until tempDay = DesData
            i = i - 1
        Else
            i = 0
        End If

        Days = i
    End Function

    '检查身份证号是否正确
    Function Identification(Text1)
    xian = Text1
    If (Not IsNumeric(Left(Text1, 15)) And Not IsNumeric(Left(Text1, 18))) Or Text1 = "" Then
      Identification = False
      Exit Function
    End If
    lenx = Len(Trim(Text1))
    If lenx = 15 Or lenx = 18 Then
        If lenx = 15 Then
            yy = "19" & Mid(xian, 7, 2)
            mm = Mid(xian, 9, 2)
            dd = Mid(xian, 11, 2)
            aa = Right(xian, 1)
        End If
        If lenx = 18 Then
            yy = Mid(xian, 7, 4)
            mm = Mid(xian, 11, 2)
            dd = Mid(xian, 13, 2)
            aa = Right(xian, 1)
        End If
        If CInt(mm) > 12 Or CInt(dd) > 31 Then
           Identification = False
           Exit Function
        Else
         Identification = True
         Exit Function
        End If
    Else
      Identification = False
      Exit Function
    End If
    End Function

    '检查是否存在数字
    Function checkString (myString)
     checkString = False
     Dim myChr
     For myChr = 48 to 57
      If InStr(myString,Chr(myChr)) > 0 Then
       checkString = True
       Exit Function
      End If
     Next
    End Function

    '查询Access数据库字符出现次数
    Function Access_GetCount(DBlocation,TableName,Value)
     set con=createobject("adodb.connection")
     con.open "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & DBlocation
     set record = createobject("adodb.recordset")
     sql="select * from " & TableName
     
     record.open sql,con
     DO
      if(record("name")=Value)then
       num=num+1
      end If
      record.MoveNext
     loop until record.eof=True
     
     record.close
     set record=Nothing
     con.close
     set con=Nothing
     
     If num = 0 Then
      Access_GetCount = 0
     Else
      Access_GetCount = num
     End If
    End Function

    '按ASCII码值冒泡排序
    Function BubbleSort(VString,Spl,Func)
     Dim Str,StrLength,i,j
     Str = Split(VString,Spl)
     StrLength = UBound(Str) + 1
     For i = 1 To (StrLength-1)
      For j = (i+1) To StrLength
       If Func = 1 then
        If Asc(Str(i-1)) < Asc(Str(j-1)) Then
         Call Swap(Str(i-1),Str(j-1))
        End If
       Else
        If Asc(Str(i-1)) > Asc(Str(j-1)) Then
         Call Swap(Str(i-1),Str(j-1))
        End If
       End If
      Next
     Next
     j = ""
     For i = 1 To StrLength
      j = j & Str(i-1) & Spl
     Next
     j = Left(j,(StrLength * 2 -1))
     BubbleSort = j
    End Function


    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '''以下为仅QuickTest适用函数'''''''''''''''''''''''''''''''''''''''''
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    '让QTP运行时保持最小化
    Public Sub QTP_Small()
     Dim objQTPWin
     Set ōbjQTPWin = GetObject("" , "QuickTest.Application")
     objQTPWin.WindowState = "Minimized"
     Set ōbjQTPWin = Nothing
    End Sub

    '恢复QTP窗口
    Public Sub QTP_Big()
     Dim objQTPWin
     Set ōbjQTPWin = GetObject("" , "QuickTest.Application")
     objQTPWin.WindowState = "Restored"
     Set ōbjQTPWin = Nothing
    End Sub

    '写文件函数(追加)
    '输入值:写入内容
    Public Function QTP_WriteFile(pathway,words) 
        Dim fileSystemObj,fileSpec,logFile,way
        Set fileSystemObj = CreateObject("scrīpting.FileSystemObject")
        fileSpec = pathway
        Set logFile = fileSystemObj.OpenTextFile(fileSpec, 8, true)
        logFile.WriteLine (CStr(words))
        logFile.Close
        Set logFile = Nothing
    End Function

    '写文件函数(改写)
    '输入值:写入内容
    Public Function QTP_WriteFile_Change(pathway,words) 
        Dim fileSystemObj,fileSpec,logFile,way
        Set fileSystemObj = CreateObject("scrīpting.FileSystemObject")
        fileSpec = pathway
        Set logFile = fileSystemObj.OpenTextFile(fileSpec, 2, true)
        logFile.WriteLine (CStr(words))
        logFile.Close
        Set logFile = Nothing
    End Function

    '读Excel文件元素
    Public Function QTP_Read_Excel(pathway,sheetname,x,y)
     Dim srcData,srcDoc,ret
     set srcData = CreateObject("Excel.Application")
     srcData.Visible = True
     set srcDoc = srcData.Workbooks.Open(pathway)
     srcDoc.Worksheets(sheetname).Activate
     ret = srcDoc.Worksheets(sheetname).Cells(x,y).value
     srcData.Workbooks.Close
     Window("text:=Microsoft Excel").Close
     QTP_Read_Excel = ret
    End Function

    '写Excel文件元素并保存退出
    Public Function QTP_Write_Excel(pathway,sheetname,x,y,content)
     Dim srcData,srcDoc,sp1,sp2,num,use,a1,a2,a3
     set srcData = CreateObject("Excel.Application")
     srcData.Visible = True
     set srcDoc = srcData.Workbooks.Open(pathway)
     srcDoc.Worksheets(sheetname).Activate
     srcDoc.Worksheets(sheetname).Cells(x,y).value = content
     
    ' sp1 = Split(pathway,".")
    ' sp2 = Split(sp1(0),"\")
    ' num = UBound(sp2)
    ' use = sp2(num)

    ' Set a1 = Descrīption.Create()
    ' a1("text").value="Microsoft Excel - " + use + ".xls"
    ' a1("window id").value="0"

    ' Set a3 = Descrīption.Create()
    ' a3("Class Name").value="WinObject"
    ' a3("text").value= use + ".xls"

    ' Window(a1).WinObject(a3).Type micCtrlDwn + "s" + micCtrlUp

     Dim WshShell
     Set WshShell=CreateObject("Wscrīpt.Shell")
     WshShell.SendKeys "^s"
     wait(1)
     
     srcData.Workbooks.Close
     Set srcDoc = nothing
     
     Window("text:=Microsoft Excel").Close
    End Function

    '定时停留弹出框函数
    Sub QTP_Msgbox(Value,waitTime,Title)
     Dim WshShell
        Set WshShell = CreateObject("Wscrīpt.Shell")
        WshShell.Popup Value, waitTime, Title
        Set WshShell = nothing
    End Sub

    '改变Excel的单元格颜色
    Public Function QTP_Change_Color(pathway,sheetname,x,y,color)
     Dim srcData,srcDoc,sp1,sp2,num,use,a1,a2,a3
     set srcData = CreateObject("Excel.Application")
     srcData.Visible = True
     set srcDoc = srcData.Workbooks.Open(pathway)
     srcDoc.Worksheets(sheetname).Activate
     If color = "red" Then
      srcDoc.Worksheets(sheetname).Cells(x,y).Interior.color=vbred
     ElseIf color = "green" Then
      srcDoc.Worksheets(sheetname).Cells(x,y).Interior.color=vbgreen
     Else
      MsgBox "输入的颜色参数不正确,只接收""red""和""green"""
     End If

     Dim WshShell
     Set WshShell=CreateObject("Wscrīpt.Shell")
     WshShell.SendKeys "^s"
     wait(1)
     
     srcData.Workbooks.Close
     Set srcDoc = nothing
     Window("text:=Microsoft Excel").Close
    End Function

    '捕获当前屏幕(截图)
    Public Function QTP_Capture(pathway)
      Dim datestamp
      Dim filename
      datestamp = Now()
      filename = Environment("TestName")&"_"&datestamp&".png"
      filename = Replace(filename,"/","")
      filename = Replace(filename,":","")
      filename = pathway + "\" + ""&filename
      Desktop.CaptureBitmap filename
      'Reporter.ReportEvent micFail,"image","<img src='" & filename & "'>"
    End Function

     

     

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '''''QuickTestPlus 帮助文件对于Excel库函数  仅QTP适用''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim ExcelApp 'As Excel.Application
    Dim excelSheet 'As Excel.worksheet
    Dim excelBook 'As Excel.workbook
    Dim fso 'As scrīpting.FileSystemObject

    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

    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

    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 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 = 1
        Else
            SaveWorkbook = 0
        End If
    End Function

    Sub SetCellValue(excelSheet, row, column, value)
        On Error Resume Next
        excelSheet.Cells(row, column) = value
        On Error GoTo 0
    End Sub

    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

    Function GetSheet(ExcelApp, sheetIdentifier) 'As Excel.worksheet
        On Error Resume Next
        Set GetSheet = ExcelApp.Worksheets.Item(sheetIdentifier)
        On Error GoTo 0
    End Function

    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)
        If sheetName <> "" Then
            worksheet.Name = sheetName
        End If
        Set InsertNewWorksheet = worksheet
    End Function

    Function CreateNewWorkbook(ExcelApp)
        Set NewWorkbook = ExcelApp.Workbooks.Add()
        Set CreateNewWorkbook = NewWorkbook
    End Function

    Function OpenWorkbook(ExcelApp, path)
        On Error Resume Next
        Set NewWorkbook = ExcelApp.Workbooks.Open(path)
        Set ōpenWorkbook = NewWorkbook
        On Error GoTo 0
    End Function


    Sub ActivateWorkbook(ExcelApp, workbookIdentifier)
        On Error Resume Next
        ExcelApp.Workbooks(workbookIdentifier).Activate
        On Error GoTo 0
    End Sub

    Sub CloseWorkbook(ExcelApp, workbookIdentifier)
        On Error Resume Next
        ExcelApp.Workbooks(workbookIdentifier).Close
        On Error GoTo 0
    End Sub

    Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow, numberOfRows, trimed) 'As Boolean
        Dim returnVal 'As Boolean
        returnVal = True
        If sheet1 Is Nothing Or sheet2 Is Nothing Then
            CompareSheets = False
            Exit Function
        End If
        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 Then
                    Value1 = Trim(Value1)
                    Value2 = Trim(Value2)
                End If
                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

     

    '写入word文件
    Sub QTP_WriteWord(pathway,content)
     Dim oWord,oRange,oDoc
     Set ōWord = CreateObject("Word.Application")
     oWord.documents.open pathway,forwriting, True
     Set ōDoc = oWord.ActiveDocument
     Set ōRange = oDoc.content
     oRange.insertafter content
     oWord.ActiveDocument.Save
    ' Dim WshShell
    ' Set WshShell=CreateObject("Wscrīpt.Shell")
    ' WshShell.SendKeys "^s"
    ' wait(1)
        oWord.Application.Quit True
     Set ōRange = Nothing
     Set ōDoc = Nothing
     Set ōWord = Nothing
    End Sub

  • QTP登录脚本

    2008-09-24 12:00:11

    我要实现的需求:验证登录成功或失败,跳转的页面是否正确。

    采用了参数化功能,以及判断语句if.....then

    调试通过。

    以sohu论坛登录为例。

    脚本如下:

    Dim right_str,error_str
    'num=DataTable.GetSheet("Global").GetRowCount
    'For i=1 to num
    Browser("搜狐社区,中文第一社区-club.sohu.com").Navigate("http://club.sohu.com/")
    Browser("搜狐社区,中文第一社区-club.sohu.com").Page("搜狐社区,中文第一社区-club.sohu.com").WebEdit("email").Set DataTable("username", dtGlobalSheet)
    Browser("搜狐社区,中文第一社区-club.sohu.com").Page("搜狐社区,中文第一社区-club.sohu.com").webedit("password").SetSecure DataTable("EncryptedText", dtGlobalSheet)
    Browser("搜狐社区,中文第一社区-club.sohu.com").Page("搜狐社区,中文第一社区-club.sohu.com").webbutton("登 录").Click
    wait(3)
    right_str=Browser("搜狐社区,中文第一社区-club.sohu.com").Page("搜狐社区,中文第一社区-club.sohu.com").WebElement("tewtewtet").Exist
    error_str=Browser("搜狐社区,中文第一社区-club.sohu.com").Page("搜狐社区,中文第一社区-club.sohu.com").WebElement("用户名或密码错误").Exist
    If  right_str Then
     msgbox"登录成功"
     Browser("搜狐社区,中文第一社区-club.sohu.com_2").Page("搜狐社区,中文第一社区-club.sohu.com").Link("退出").Click
     elseif error_str  then
     msgbox"登录失败"
    End If

Open Toolbar