ITF Demo代码(用VBScript构建的接口测试框架)

'#########################################################
' 整合GCov
Function Example_GCov

 Call GCov_Build_With_Coverage()
 Call GCov_Run_AUT()
 Call GCov_Gen_Coverage_Data()
 Call LCov_Gen_Report()
 Call GCov_LCov_DownLoad_Report()
 
End Function


'#########################################################
' 整合soapUI的例子
Function Example_SoapUI()

 project = "D:\WebService\soapUI\projects\Hotel-ReservationService-soapui-project.xml"
 report = "D:\1"
 TestCase = "TestCase2"
 Call Invoke_SoapUI_Project_TestCase(project , report , TestCase )

End Function


' 整合soapUI
Function Invoke_SoapUI_Project_TestCase( project , report , TestCase )

 ' 调用soapUI命令行
 Dim oShell
 Set oShell = WScript.CreateObject ("WSCript.shell")
 cmd = """E:\Program Files\SmartBear\soapUI-4.5.1\bin\testrunner.bat"" " & project & "  -c " & TestCase & " -a -r -f" & report & " >"& report & "\summery.txt"
 oShell.Run cmd , 0 , True
 Set oShell = Nothing
 
 ' 读取soapUI输出的Log
 'logText = ReadResultFromFile( report & "\output.txt" )
 'MsgBox logText
 ' 写入测试日志文件
 'Log logText 
 
End Function


'#########################################################
' 整合LoadRunner的例子
Function Example_LoadRunner()
  usrFile = "F:\ATMS\LR接口测试框架\SocketTest\SocketTest.usr"
  outFile = "F:\ATMS\LR接口测试框架\SocketTest\out"
  parmList = " -remoteHost ""127.0.0.1"" -port ""1234"" -data ""hello"" -CheckResponseContains ""Server to Client String"""
  Invoke_LoadRunner usrFile, outFile , parmList
End Function


' 整合LoadRunner
Function Invoke_LoadRunner(usrFile , outFile , parmList )
    usr = " -usr " & usrFile
    out = " -out " & outFile
 
 ' 调用LR命令行
 Dim oShell
 Set oShell = WScript.CreateObject ("WSCript.shell")
 oShell.Run """E:\Program Files\HP\LoadRunner\bin\mdrv.exe""" & usr & out &  parmList , 0 , True
 Set oShell = Nothing
 
 ' 读取LR输出的Log
 logText = ReadResultFromFile( outFile & "\output.txt" )
 'MsgBox logText
 ' 写入测试日志文件
 Log logText 
End Function


'#########################################################
' MD5加密
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)

m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)

Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function

Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function

Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function

Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function

Private Function F(x, y, z)
F = (x And y) Or ((Not x) And z)
End Function
Private Function G(x, y, z)
G = (x And z) Or (y And (Not z))
End Function
Private Function H(x, y, z)
H = (x Xor y Xor z)
End Function
Private Function I(x, y, z)
I = (y Xor (x Or (Not z)))
End Function

Private Sub FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub

Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function

Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function

Public Function MD5(sMessage)
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
FF a, b, c, d, x(k + 0), S11, &HD76AA478
FF d, a, b, c, x(k + 1), S12, &HE8C7B756
FF c, d, a, b, x(k + 2), S13, &H242070DB
FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
FF d, a, b, c, x(k + 5), S12, &H4787C62A
FF c, d, a, b, x(k + 6), S13, &HA8304613
FF b, c, d, a, x(k + 7), S14, &HFD469501
FF a, b, c, d, x(k + 8), S11, &H698098D8
FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
FF b, c, d, a, x(k + 11), S14, &H895CD7BE
FF a, b, c, d, x(k + 12), S11, &H6B901122
FF d, a, b, c, x(k + 13), S12, &HFD987193
FF c, d, a, b, x(k + 14), S13, &HA679438E
FF b, c, d, a, x(k + 15), S14, &H49B40821
GG a, b, c, d, x(k + 1), S21, &HF61E2562
GG d, a, b, c, x(k + 6), S22, &HC040B340
GG c, d, a, b, x(k + 11), S23, &H265E5A51
GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
GG a, b, c, d, x(k + 5), S21, &HD62F105D
GG d, a, b, c, x(k + 10), S22, &H2441453
GG c, d, a, b, x(k + 15), S23, &HD8A1E681
GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
GG d, a, b, c, x(k + 14), S22, &HC33707D6
GG c, d, a, b, x(k + 3), S23, &HF4D50D87
GG b, c, d, a, x(k + 8), S24, &H455A14ED
GG a, b, c, d, x(k + 13), S21, &HA9E3E905
GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
GG c, d, a, b, x(k + 7), S23, &H676F02D9
GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
HH a, b, c, d, x(k + 5), S31, &HFFFA3942
HH d, a, b, c, x(k + 8), S32, &H8771F681
HH c, d, a, b, x(k + 11), S33, &H6D9D6122
HH b, c, d, a, x(k + 14), S34, &HFDE5380C
HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
HH a, b, c, d, x(k + 13), S31, &H289B7EC6
HH d, a, b, c, x(k + 0), S32, &HEAA127FA
HH c, d, a, b, x(k + 3), S33, &HD4EF3085
HH b, c, d, a, x(k + 6), S34, &H4881D05
HH a, b, c, d, x(k + 9), S31, &HD9D4D039
HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
HH b, c, d, a, x(k + 2), S34, &HC4AC5665
II a, b, c, d, x(k + 0), S41, &HF4292244
II d, a, b, c, x(k + 7), S42, &H432AFF97
II c, d, a, b, x(k + 14), S43, &HAB9423A7
II b, c, d, a, x(k + 5), S44, &HFC93A039
II a, b, c, d, x(k + 12), S41, &H655B59C3
II d, a, b, c, x(k + 3), S42, &H8F0CCC92
II c, d, a, b, x(k + 10), S43, &HFFEFF47D
II b, c, d, a, x(k + 1), S44, &H85845DD1
II a, b, c, d, x(k + 8), S41, &H6FA87E4F
II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
II c, d, a, b, x(k + 6), S43, &HA3014314
II b, c, d, a, x(k + 13), S44, &H4E0811A1
II a, b, c, d, x(k + 4), S41, &HF7537E82
II d, a, b, c, x(k + 11), S42, &HBD3AF235
II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next

MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
End Function

'#########################################################
Function Example_TestMD5()
  MsgBox MD5("admin")
End Function


'#########################################################
' 设置Mock服务器响应
Function setMock( url , expected_Response )
 Http_Post url , expected_Response
End Function


'#########################################################
' HTTP发包核心引擎 - Get请求
Function Http_Get( URL )

  sContentType = "text/xml;charset=utf-8"
 
  Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
  oWinHttpReq.Open "Get", URL, False
  oWinHttpReq.setRequestHeader "Content-Type", sContentType
 
  oWinHttpReq.Send
 
  sStatusCode = oWinHttpReq.Status()
  MsgBox sStatusCode
  sResponseHeader = oWinHttpReq.GetAllResponseHeaders()
  MsgBox sResponseHeader

  sResponseBody = oWinHttpReq.ResponseText
  MsgBox sResponseBody

  set oWinHttpReq = Nothing

End Function

'#########################################################
' HTTP发包核心引擎 - Post请求
Function Http_Post( URL ,Request )

  sContentType = "text/xml;charset=utf-8"
 
  Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
  oWinHttpReq.Open "Post", URL, False
  oWinHttpReq.setRequestHeader "Content-Type", sContentType
 
  oWinHttpReq.Send Request
 
  sStatusCode = oWinHttpReq.Status()
  MsgBox sStatusCode
  sResponseHeader = oWinHttpReq.GetAllResponseHeaders()
  MsgBox sResponseHeader

  sResponseBody = oWinHttpReq.ResponseText
  MsgBox sResponseBody

  set oWinHttpReq = Nothing

End Function


'#########################################################
' 重置覆盖率统计
Function Example_BullseyeCoverage_Reset
 ExecuteCmd "UDPSend.bat covclear"
End Function

'#########################################################
' 获取覆盖率统计(FTP下载)
Function Example_BullseyeCoverage_GetFile
 ExecuteCmd "UDPSend.bat covxml"
 ExecuteCmd "FTP_GetFile.bat"
End Function 

 

'#########################################################
Function Example_SendMail

 SendMail "F:\ATMS\VBS接口测试框架\log.txt"

End Function

'#########################################################
' 发送Email
Function SendMail(LogFile)

    ' 从配置文件读入各种参数
    Set ConfigParameters = CreateObject("Scripting.Dictionary")
    ConfigFile = "config.ini"
    ReadTestsFromConfigFile ConfigFile , ConfigParameters

 Set oMessage=WScript.CreateObject("CDO.Message")
 Set oConf=WScript.CreateObject("CDO.Configuration")
 Set fso = CreateObject("Scripting.FileSystemObject")
 
 '创建CDO.Configuration对象后,需要设置邮件服务器的端口、用户帐号等相关信息
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver")=ConfigParameters.Item("smtpserver")
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/serverport")=25
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername")=ConfigParameters.Item("sendusername")
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword")=ConfigParameters.Item("sendpassword")
 oConf.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl")=0
 oConf.Fields.Update()
 
 '通过CDO的 Message对象设置邮件主题、附件、发送人等信息
 oMessage.Configuration = oConf
 oMessage.To = ConfigParameters.Item("Email_Address")
 oMessage.From = ConfigParameters.Item("sendusername")
 oMessage.Subject = "ITF Testing Notification"
 file = fso.GetAbsolutePathName(LogFile)
 Set fso = Nothing
 oMessage.AddAttachment( file )

 TextBody = "ITF Test Finish! See attachment for logs."  
 oMessage.TextBody = TextBody
 oMessage.Send()
 
End Function

'----------------------------------------------------------------------------------
' 读取配置文件
Function ReadTestsFromConfigFile( ByVal ConfigFile , ByRef ConfigParameters )
 Set GetParameters = ConfigParameters
 Dim fso, f, lineStr, isValid
 Set fso = CreateObject("Scripting.FileSystemObject") 
 If Not fso.FileExists(ConfigFile) Then
  Response ConfigFile & " not found"
  Exit Function
 End If

 Set f=fso.OpenTextFile(ConfigFile,1,False)  'Open file for read, if not existed, don't created it.
 Do While f.AtEndOfStream <> True
  lineStr = f.ReadLine()  
   lineStr=Trim(lineStr)
   If lineStr<>"" Then  'not empty line
   If InStr(1,lineStr,"smtpserver=") = 1 Then
    smtpserver = Trim(Right(lineStr,Len(lineStr)-11))
    GetParameters.Add "smtpserver", smtpserver
   ElseIf InStr(1,lineStr,"sendusername=") = 1 Then
    sendusername = Trim(Right(lineStr,Len(lineStr)-13))
    GetParameters.Add "sendusername", sendusername
   ElseIf InStr(1,lineStr,"sendpassword=") = 1 Then
    sendpassword = Trim(Right(lineStr,Len(lineStr)-13))
    GetParameters.Add "sendpassword", sendpassword
   ElseIf InStr(1,lineStr,"Email_Address=") = 1 Then
    Email_Address = Trim(Right(lineStr,Len(lineStr)-14))
    GetParameters.Add "Email_Address", Email_Address
   End If
   End If
 Loop 
 f.Close

 Set ReadTestsFromConfigFile = GetParameters 
End Function

 

'#########################################################
' 测试写Log的例子
Sub Example_TestLog

 Call Log("MyLog Test!")

End Sub

'#########################################################
' 写文本文件日志
Function Log( logText )

  Set fso = CreateObject("Scripting.FileSystemObject")
  Set logFile = fso.OpenTextFile("log.txt", 8, true) ' 8 - ForAppending
 
  logFile.WriteLine(Time() & ":" & logText)

  logFile.Close
  Set logFile = Nothing
  Set fso = Nothing

End Function


'#########################################################
' 测试Excel数据驱动的例子
Sub Example_WebService_ExcelDataDriven

 Execute_WebService_ExcelDataDriven "TestCase1.xls" , "WebServiceTest"
 Execute_WebService_ExcelDataDriven "TestCase2.xls" , "WebServiceTest"
 Execute_WebService_ExcelDataDriven "TestCase3.xls" , "WebServiceTest"
 
End Sub


'#########################################################
' 读取Excel文件测试用例,执行WebService接口测试
Sub Execute_WebService_ExcelDataDriven( ExcelFile , SheetName)

  On Error Resume Next
 
  Set conn = createobject("ADODB.Connection")
  conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& ExcelFile &";Extended Properties=Excel 8.0"
 
  sql= "SELECT * FROM [" & SheetName & "$]"
  Set RecSet = conn.Execute(sql)
  RecSet.MoveFirst
 
  While Not RecSet.EOF
     Call WebService_SendData( RecSet.Fields("url").Value , RecSet.Fields("soap_action").Value , RecSet.Fields("soap_data").Value , RecSet.Fields("check_response_statuscode").Value , RecSet.Fields("Assert_Contains").Value )
     RecSet.MoveNext
  Wend
 
  conn.close
  Set conn = Nothing
 
End Sub


'#########################################################
' WebService发包核心引擎
Function WebService_SendData( sWebService_Url , sSOAPAction , sSOAP_Request , checkCode , checkContains)
  On Error Resume Next
 
  sContentType = "text/xml;charset=utf-8"
 
  Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
  oWinHttpReq.Open "POST", sWebService_Url, False
  oWinHttpReq.setRequestHeader "Content-Type", sContentType
  If IsNull(sSOAPAction) Then
   oWinHttpReq.setRequestHeader "SOAPAction", " "
  Else
   oWinHttpReq.setRequestHeader "SOAPAction", sSOAPAction
  End If
   
  oWinHttpReq.Send  sSOAP_Request
  Log( "SOAP_Request - " & sSOAPAction )

  '检查响应码
  sStatusCode = oWinHttpReq.Status()
  'MsgBox Assert_Equal(sStatusCode, checkCode)

  '获取 XML 响应头
  sResponseHeader = oWinHttpReq.GetAllResponseHeaders()
  'MsgBox  "ResponseHeader=" & sResponseHeader

  '获取 XML 响应文本
  sXMLResponse = oWinHttpReq.ResponseText
  MsgBox sXMLResponse
  MsgBox Assert_Contains( sXMLResponse , checkContains )

  set oWinHttpReq = Nothing

End Function


'#########################################################
' 测试调用AutoIt发送Socket的例子
Sub Example_TestSocket

  ExecuteCmd("TCPTest.bat")

End Sub

'#########################################################
' 测试调用AutoIt的例子

Sub Example_TestAutoIt

  Set oShell = WScript.CreateObject("WScript.Shell")
  Set oAutoIt = WScript.CreateObject("AutoItX3.Control")
 
  oShell.Run "Calc.exe"
 
  oAutoIt.WinWait "[CLASS:SciCalc]"
  oAutoIt.WinActivate "[CLASS:SciCalc]" , "计算器"

  oAutoIt.Send "!h"
  oAutoIt.Send "a"
 
  oAutoIt.Sleep 2000
 
  title = "关于 计算器"
  ok_contrl = "[CLASS:Button;TEXT:确定]"
  oAutoIt.WinActivate title
  oAutoIt.ControlClick title ,"",ok_contrl
 
  oAutoIt.Sleep 2000
   
  oAutoIt.WinClose "计算器"
 
  Set oAutoIt = Nothing
  Set oShell = Nothing
End Sub


'#########################################################
' 测试连接SSH的例子

Sub Example_TestSSH

  MsgBox ExecuteCmd( "G:\接口测试解决方案\VBS接口测试框架\SSH.bat" )

End Sub

'#########################################################
' GCov编译插桩
Sub GCov_Build_With_Coverage
 '编译被测程序:
 'gcc bubblesort.c -o bubblesort -ftest-coverage -fprofile-arcs
 '生成bubblesort.gcno 和 bubblesort可执行文件
 
  ExecuteCmd( "ExecuteSSH.bat  F:\ATMS\VBS接口测试框架\BuildWithCoverage.vbs" )

End Sub

'#########################################################
' 执行插桩后的AUT
Sub GCov_Run_AUT
 '运行bubblesort,生成 bubblesort.gcda 文件
 
  ExecuteCmd( "ExecuteSSH.bat  F:\ATMS\VBS接口测试框架\SSH_Execute_AUT.vbs" )

End Sub

'#########################################################
' 用gcov生成覆盖率报告文件
Sub GCov_Gen_Coverage_Data
 '用gcov生成覆盖率报告文件 bubblesort.c.gcov
 
  ExecuteCmd( "ExecuteSSH.bat  F:\ATMS\VBS接口测试框架\SSH_GCov_Gen.vbs" )

End Sub

'#########################################################
' 用lcov生成覆盖率信息文件
Sub LCov_Gen_Report
 '用lcov生成覆盖率信息文件 lcov -c -o bubblesort.info -d .
 '生成html格式的覆盖率报告 genhtml bubblesort.info -o bubblesort_result
  ExecuteCmd( "ExecuteSSH.bat  F:\ATMS\VBS接口测试框架\SSH_LCov_Gen_Report.vbs" )

End Sub

'#########################################################
' 下载覆盖率报告
Sub GCov_LCov_DownLoad_Report

  ExecuteCmd( "ExecuteSSH.bat  F:\ATMS\VBS接口测试框架\GCov_LCov_DownLoad_Report.vbs" )

End Sub

'#########################################################

' 测试WebService的例子

Sub Example_TestWebService

Dim sContentType, sSOAPAction,sWebService_Url,oWinHttpReq
Dim sSOAP_Request,sXMLResponse
' 定义SOAP请求
sContentType = "text/xml;charset=utf-8"
sSOAPAction = "http://WebXml.com.cn/getSupportCity"
sWebService_Url = "http://www.webxml.com.cn/Webservices/WeatherWebService.asmx"
sSOAP_Request = "<?xml version=""1.0"" encoding=""utf-8""?>" &_
"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" &_
  "<soap:Body>" &_
    "<getSupportCity xmlns=""http://WebXml.com.cn/"">" &_
      "<byProvinceName>广东</byProvinceName>" &_
    "</getSupportCity>" &_
  "</soap:Body>" &_
"</soap:Envelope>"

' 创建WinHttp.WinHttpRequest.5.1 对象
Set oWinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
oWinHttpReq.Open "POST", sWebService_Url, False
oWinHttpReq.setRequestHeader "Content-Type", sContentType
oWinHttpReq.setRequestHeader "SOAPAction", sSOAPAction


' 发送SOAP 请求
oWinHttpReq.Send  sSOAP_Request


'获取 XML 响应状态码
sStatusCode = oWinHttpReq.Status()
' 检查响应码=200
MsgBox "Status=200:" & Assert_Equal_Number(sStatusCode,200)


'获取 XML 响应头
sResponseHeader = oWinHttpReq.GetAllResponseHeaders()
MsgBox  "ResponseHeader=" & sResponseHeader

'获取 XML 响应文本
sXMLResponse = oWinHttpReq.ResponseText
'Msgbox  sXMLResponse

' 创建Msxml2.DOMDocument对象
Set oInputXmlDoc = CreateObject("Msxml2.DOMDocument")

' 加载XML数据
oInputXmlDoc.loadXML(sXMLResponse)


MsgBox "getElementByTagName(string) = 22 : " & Assert_Equal_ElementByTagName_ItemCount(oInputXmlDoc,"string",22)
MsgBox "getElementByTagName(string).Item(0) = 广州 (59287) : " & Assert_Equal_ElementByTagName_ItemText(oInputXmlDoc,"string",0,"广州 (59287)")


' 访问XML节点数据
MsgBox  oInputXmlDoc.childNodes(1).text

MyStr = oInputXmlDoc.childNodes(1).text
MyStrArr = Split(MyStr , " ")
MsgBox MyStrArr(1)

Msgbox Assert_Equal( MyStrArr(1) ,"(59287)深圳")
Msgbox Assert_Contains( MyStrArr(1), "深圳" )

set oInputXmlDoc = Nothing
set oWinHttpReq = Nothing

End Sub

 

'##################################################
' 测试命令行接口的例子

Sub Example_TestCmd
 
  MsgBox ExecuteCmd( "G:\接口测试解决方案\VBS接口测试框架\TestPing.bat" )
 
  MsgBox Assert_Cmd_Output_Result_OK( "G:\接口测试解决方案\VBS接口测试框架\TestPing.bat" , "G:\接口测试解决方案\VBS接口测试框架\log.txt" )
 
  MsgBox Get_Cmd_Output_Result( "G:\接口测试解决方案\VBS接口测试框架\TestPing.bat" , "G:\接口测试解决方案\VBS接口测试框架\log.txt" )
 
End Sub

 

'#########################################################
' 测试Oracle数据库的例子
Sub Example_TestOracle
 
  MsgBox Assert_Equal_DB_TableRow_Number("EMP")
  MsgBox Assert_Equal_DB_Cell_Value("EMP",0,0,"7369")
 
End Sub

 

'##################################################

' 库函数

' 判断字符串相等
Function Assert_Equal( Actual_Str , Expect_Str )
  Assert_Equal = StrComp( Actual_Str  , Expect_Str , vbTextCompare)
End Function


' 判断字符串包含
Function Assert_Contains( Str , Expect_Str )
  IF InStr( Str , Expect_Str ) > 0 Then
    Log "Check Pass: Contains " & Expect_Str
    Assert_Contains = True
  Else
    Log "Check Fail: NOT Contains " & Expect_Str
    Assert_Contains = False
  End IF
End Function


' 判断数字相等
Function Assert_Equal_Number( Actual_Num , Expect_Num )
  If (Actual_Num = Expect_Num) Then
    Assert_Equal_Number = True
  Else
    Assert_Equal_Number = False
  End If
End Function


' 判断XML文档中指定标签名的项数是否等于预期值
Function Assert_Equal_ElementByTagName_ItemCount( oInputXmlDoc , TagName , Expect_ItemCount )
  If (oInputXmlDoc.getElementsByTagName(TagName).length = Expect_ItemCount) Then
    Assert_Equal_ElementByTagName_ItemCount = True
  Else
    Assert_Equal_ElementByTagName_ItemCount = False
  End If
End Function


' 判断XML文档中指定标签名的某项值是否等于预期值
Function Assert_Equal_ElementByTagName_ItemText( oInputXmlDoc , TagName , ItemIndex , Expect_ItemText )
  If oInputXmlDoc.getElementsByTagName(TagName).item(ItemIndex).text = Expect_ItemText Then
   Assert_Equal_ElementByTagName_ItemText = True
  Else
    Assert_Equal_ElementByTagName_ItemText = False
  End If 
End Function


'##################################################

' 从文件读取所有文本
Function ReadResultFromFile( FilePath )
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set outputfile = fso.OpenTextFile(FilePath,1,false)
  ReadResultFromFile =  outputfile.ReadAll()
  Set outputfile = Nothing
  Set fso = Nothing
End Function

' 执行命令行调用批处理文件
Function ExecuteCmd( CmdBatFile )
 Set oShell = WScript.CreateObject("WScript.Shell")
  Return  = oShell.Run( CmdBatFile , 0, True )
  WScript.Sleep 3000
  If Return = 0 Then
    ExecuteCmd = True
  Else   
    ExecuteCmd = False
  End If
  Set oShell = Nothing
End Function

' 判断命令行接口调用是否成功返回
Function Assert_Cmd_Output_Result_OK(CmdBatFile,CmdOutputFile)
  Set oShell = WScript.CreateObject("WScript.Shell")
  Return  = oShell.Run( CmdBatFile , 0, True )
  'Msgbox Return ' 正常执行应该返回 0
  WScript.Sleep 3000
  If Return = 0 Then
    'Msgbox "执行成功,返回结果:" & ReadResultFromFile(CmdOutputFile)
    Assert_Cmd_Output_Result_OK = True
  Else
    'Msgbox "执行失败,返回结果:" & ReadResultFromFile(CmdOutputFile)
    Assert_Cmd_Output_Result_OK = False
  End If
  Set oShell = Nothing
End Function

' 执行命令行接口调用并获取输出结果
Function Get_Cmd_Output_Result(CmdBatFile,CmdOutputFile)
  Set oShell = WScript.CreateObject("WScript.Shell")
  Return  = oShell.Run( CmdBatFile , 0, True )
  WScript.Sleep 3000
  Get_Cmd_Output_Result = ReadResultFromFile(CmdOutputFile)
  Set oShell = Nothing
End Function

'##################################################
' Oracle数据库检查点

' 判断Oracle数据库表行记录个数
Function Assert_Equal_DB_TableRow_Number( TableName )
  Dim rs,sq,pkey
  Set conn=createobject("adodb.connection")
  Set rs=createobject("adodb.recordset")

  ' 需要安装Oracle客户端
  'conn.open "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;User ID=scott;Data Source=orcl;Password=orcl;Extended Properties=;Host=192.168.40.148;Port=1521;Service Name=orcl;"
  'conn.open "DRIVER={Microsoft ODBC for Oracle};SERVER=192.168.40.148;User Id=scott;Password=orcl;"
  conn.Open "Provider=MSDAORA.Oracle;Data Source=orcl;user id=scott;password=orcl"
 
  sql="SELECT COUNT(*) FROM "& TableName
  rs.open sql,conn
  rs.MoveFirst
  TableRowCount = 0
  Do While rs.Eof<>true
    TableRowCount = rs.Fields(0)
    rs.MoveNext
  Loop
  rs.close

  Set rs=nothing
  conn.close
  Set conn=nothing
  Assert_Equal_DB_TableRow_Number = TableRowCount
End Function

' 判断指定表格中的某行某列的数据与预期值相等
Function Assert_Equal_DB_Cell_Value( TableName , RowIndex , ColumnIndex , ExpectedText )

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

  conn.Open "Provider=MSDAORA.Oracle;Data Source=orcl;user id=scott;password=orcl"
 
  sql="SELECT * FROM " & TableName
  rs.open sql,conn
  rs.MoveFirst
  CurrentRow = 0
  isEqual = False
  Do While rs.EOF <> True
    'MsgBox rs.Fields(ColumnIndex).Value
    If ( CurrentRow = RowIndex ) Then
      If  CStr(rs.Fields(ColumnIndex).Value) = ExpectedText Then
        isEqual = True  
        Exit Do
      End If
    End If
    rs.MoveNext
    CurrentRow = CurrentRow + 1
  Loop
  rs.close

  Set rs=nothing
  conn.close
  Set conn=nothing
  Assert_Equal_DB_Cell_Value = isEqual
 
End Function

 

'#########################################################
' 读取Excel文件测试用例,执行WebService接口测试
Sub Execute_WebService_DataTemplate( ExcelFile , SheetName)

  Set conn = createobject("ADODB.Connection")
  conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& ExcelFile &";Extended Properties=Excel 8.0"
 
  sql= "SELECT * FROM [" & SheetName & "$]"
  Set RecSet = conn.Execute(sql)
  RecSet.MoveFirst 
  While Not RecSet.EOF
      Dim soap_data
      soap_data = RecSet.Fields("soap_data").Value
      If InStr( soap_data , ".xls" ) > 0 Then
          Dim soap_data_Temp
         Set myconn = createobject("ADODB.Connection")
      myconn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& soap_data &";Extended Properties=Excel 8.0"
      mysql= "SELECT * FROM [data_template$]"
      Set myRecSet = myconn.Execute(mysql)
      myRecSet.MoveFirst
      While Not myRecSet.EOF
       soap_data_Temp = myRecSet.Fields("data_template").Value
       myRecSet.MoveNext
      Wend
      myconn.Close
      Set myconn = Nothing
           
      Set conn2 = createobject("ADODB.Connection")
      conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& soap_data &";Extended Properties=Excel 8.0"
      sql2= "SELECT * FROM [TestData$]"
      Set RecSet2 = conn2.Execute(sql2)
      RecSet2.MoveFirst
      Dim Param1,check_response_statuscode,check_contains_data
      While Not RecSet2.EOF
        ' 这里还要再完善,做到Template中有几个参数,就动态从TestData中对应的参数列替换
       Param1 = RecSet2.Fields.Item(0).Value
       check_response_statuscode = RecSet2.Fields("check_response_statuscode").Value
        check_contains_data = RecSet2.Fields("Assert_Contains").Value     
        MyString = Replace(soap_data_Temp, "#P_ProvinceName#", Param1)
         'MsgBox MyString
        
        Call WebService_SendData( RecSet.Fields("url").Value , RecSet.Fields("soap_action").Value , MyString , check_response_statuscode , check_contains_data )
       
       RecSet2.MoveNext
      Wend
      conn2.Close
      Set conn2 = Nothing
   
    Else
   
      Call WebService_SendData( RecSet.Fields("url").Value , RecSet.Fields("soap_action").Value , RecSet.Fields("soap_data").Value , RecSet.Fields("check_response_statuscode").Value , RecSet.Fields("Assert_Contains").Value )
     
     End If
    
     RecSet.MoveNext
  Wend
 
  conn.close
  Set conn = Nothing
 
End Sub


Function Example_DataTemplate()
  Execute_WebService_DataTemplate "TestCase4.xls" , "WebServiceTest"

End Function

 

'##################################################
' ITF使用例子
'##################################################

'Call Example_TestWebService   ' 测试WebService的例子
'Call Example_WebService_ExcelDataDriven ' Excel数据驱动测试WebService的例子
'Call Example_DataTemplate

'Call Example_TestAutoIt '调用AutoIt
Call Example_TestSocket


'Call Example_TestCmd ' 测试命令行接口的例子
'Call Example_TestSSH

'Call Example_TestOracle

'Call Example_BullseyeCoverage_Reset
'Call Example_WebService_ExcelDataDriven
'Call Example_BullseyeCoverage_GetFile

'setMock "http://localhost:8080/__admin/mappings/new" , "{ ""request"": { ""url"": ""/get/this"", ""method"": ""GET"" }, ""response"": { ""status"": 200, ""body"": ""Here it is!\n"" }}"
'Http_Get "http://localhost:8080/get/this"
'Http_Get "http://localhost:8080/api/mytest3?a=1"

'Call Example_TestLog
'Call Example_SendMail
'Call Example_TestMD5

'Call Example_LoadRunner
'Call Example_SoapUI
'Call Example_GCov

 

 

你可能感兴趣的:(ITF Demo代码(用VBScript构建的接口测试框架))